类有数据属性和方法属性:
属性就是 一个对象的数据成员或者函数成员。
类的数据属性只有被类的实例引用后去更新或者被类定义的可以访问这个数据属性的方法去改变( 也要通过类的实例化)。
也可以说,类的数据属性是跟类绑定的,类的数据属性是不受任何实例化的对象所影响的。
有两种方法可以去访问类的属性,一种是dir(),一种是 class.__dict__属性
dir() 可以看到对象的属性的名字列表。
类的内置属性 __dict__ 则可以返回一个字典,对应的是 属性名 键值 的对应关系 。也就是返回的是对象的属性名和属性值的对应关系。
下面是个简单的对类的 dir() 和 类的内置 __dict__方法看到的属性不同的代码例子:
[root@puppet-master-231-test eg_4]# cat !$
cat class_property.py
#coding:utf-8
class demo(object):
'demo for class property'
def __init__(self,testname):
self.name = testname
def update_name(self,newname):
self.name = newname
print dir(demo)
print
print demo.__dict__
[root@puppet-master-231-test eg_4]#
[root@puppet-master-231-test eg_4]#
[root@puppet-master-231-test eg_4]#
[root@puppet-master-231-test eg_4]#
[root@puppet-master-231-test eg_4]# python2.7 class_property.py
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'update_name']
{'update_name': <function update_name at 0x7febc61b4c80>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'demo' objects>, '__weakref__': <attribute '__weakref__' of 'demo' objects>, '__doc__': 'demo for class property', '__init__': <function __init__ at 0x7febc61b4c08>}
转载于:https://blog.51cto.com/khaozi/1858503