python 類 二: 類的屬性


類有數據屬性和方法屬性:


屬性就是 一個對象的數據成員或者函數成員。


類的數據屬性只有被類的實例引用後去更新或者被類定義的可以訪問這個數據屬性的方法去改變( 也要通過類的實例化)。


也可以說,類的數據屬性是跟類綁定的,類的數據屬性是不受任何實例化的對象所影響的。


有兩種方法可以去訪問類的屬性,一種是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>}


  

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章