您的位置:首页 > 编程语言 > Python开发

python的实例属性与类属性

2018-03-02 14:37 211 查看
不说废话,上代码(python3)。class Cls:
common = 7 #静态变量,在Cls的__dict__里面

def __init__(self): #实例方法,在Cls的__dict__里面
self.age = 5 #实例属性,在实例的__dict__

def f(self): #实例方法,在Cls的__dict__里面
return self.age

>>> dir(Cls)
['__class__', '__dict__', '__init__', 'common', 'f', ...]
>>> Cls.__dict__
mappingproxy({'common': 7, '__init__': <function Cls.__init__ at 0x6ffffe2a620>, 'f': <function Cls.f at 0x6ffffe2a6a8>, '__dict__': <attribute '__dict__' of 'Cls' objects>, ...})
>>> Cls.__class__
<class 'type'>

>>> c=Cls()
>>> dir(c)
['__class__', '__dict__', '__init__', 'age', 'common', 'f']
>>> c.__dict__
{'age': 5}
>>> c.common = 1
>>> c.__dict__
{'age': 5, 'common': 1}
>>> c.__class__
<class '__main__.Cls'>

#如何修改类的已有方法或者添加新方法?
>>> def g(x): return x.age + 1
>>> Cls.f = g #注意这里是Cls.f而不是c.f
>>> c.f()
6
#如果这样改会怎样?
>>> c.f = g
>>> c.f() #抛异常,缺少参数
>>> c.f(c) #OK,但是不方便
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 对象