python 类变量修改_python 四种方法修改类变量,实例对象调用类方法改变类属性的值,类对象调用类方法改变类属性的值,调用实例方法改变类属性的值,直接修改类属性的值...

三种方法修改类变量,实例对象调用类方法改变类属性的值,类对象调用类方法改变类属性的值,调用实例方法改变类属性的值,类名就是类对象,city就是类变量,

#coding=utf-8

class employee(object) :

city = 'BJ' #类属性

def __init__(self, name) :

self.name = name #实例变量

#定义类方法

@classmethod

def getCity(cls) :

return cls.city

#定义类方法

@classmethod

def setCity(cls, city) :

cls.city = city

#实例方法

def set_City(self, city) :

employee.city = city

emp = employee('joy') #创建类的实例

print emp.getCity() #通过实例对象引用类方法

print employee.getCity()#通过类对象引用类方法

emp.setCity('TJ')#实例对象调用类方法改变类属性的值

print emp.getCity()

print employee.getCity()

employee.setCity('CD')#类对象调用类方法改变类属性的值

print emp.getCity()

print employee.getCity()

emp.set_City('SH')#调用实例方法改变类属性的值

print emp.getCity()

print employee.getCity()

employee.city = 20 #直接修改类属性的值

print emp.getCity()

print employee.getCity()

c:\Python27\Scripts>python task_test.py

BJ

BJ

TJ

TJ

CD

CD

SH

SH

20

20

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值