1. 程式人生 > >python之Class屬性定義和訪問

python之Class屬性定義和訪問

1、python中類定義:

類的宣告和函式的宣告形式是差不多的,開始都是關鍵字+自定義名稱
定義例項變數:可以在定義方法的時候直接定義,也可以使用例項來定義
可以使用dir(ClassName) ClassName.__dict__來檢視有哪些類屬性

      class ClassName:
      'the discription of this class'#這個是類文件說明字串
          foo='static attribute'#在定義類的時候直接定義屬性,這個屬性是類屬性,也就是說是靜態的.
          def aMethod(self,parameter)
:
#這裡定義的方法是例項的方法,也就是跟物件例項繫結的 'discription of this method'#這是方法說明字串 ClassName.foo='changed static attribute'#訪問靜態屬性可以使用ClassName.foo, #當然也可以使用self.foo來當做例項變數來訪問 self.foo='instance attribute'#訪問例項屬性

例項1靜態變數:

 fo=10
#這個是全域性變數 class ClassName(object): """docstring for ClassName""" fo=1 def foun(self2): print(ClassName.fo)#輸出1 def __init__(self): global fo #使用global可以訪問到全域性變數 fo+=1 #訪問全域性變數,python中的全域性變數就是檔案中直接定義的變數與函式和類的位置關係都是並列的 print(fo) #輸出11 ClassName.fo+=1
#類變數加一 # instance2=ClassName() # print(instance2.foo) print(ClassName().fo)#輸出2 print(ClassName().fo)#輸出3 x=60 #這個是全域性變數 def func(): global x print(x) x=90 print(x)

例項2例項變數:

class ClassName(object):
    """docstring for ClassName"""
    fo=1
    def __init__(self):
        self.fo+=1#例項變數加一,類變數並沒有改變
print(ClassName().fo)#輸出2
print(ClassName().fo)#輸出2
print(ClassName.fo)#輸出1,這裡訪問類變數並沒有因為self.fo+=1而改變
print(ClassName.fo)#輸出1

例項3例項變數:

class ClassName(object):
    """docstring for ClassName"""
    def __init__(self):
        self.fo=1#例項變數
instance1=ClassName()
instance1.foo='instance attribute,can\'t be accessed by class'
print(dir(ClassName))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
並沒有foo和fo

例項4定義例項變數:

class ClassName(object):
    """docstring for ClassName"""
    def __init__(self):
        self.fo=1            #定義類時定義例項變數
    def fun(self):
        attribute1='instance1'   #定義類時定義例項變數
instance1=ClassName()
instance1.foo='instance attribute,can\'t be accessed by class'  #使用例項定義例項變數
print(ClassName.__dict__)
輸出:
{'__dict__': <attribute '__dict__' of 'ClassName' objects>, '__weakref__': <attribute '__weakref__' of 'ClassName' objects>, '__doc__': 'docstring for ClassName', '__module__': '__main__', '__init__': <function ClassName.__init__ at 0x035194F8>, 'fun': <function ClassName.fun at 0x035195D0>}

print(ClassName.attribute1)
發生錯誤:
AttributeError: type object 'ClassName' has no attribute 'attribute1'

2、如何得知類的屬性有哪些?
使用內建函式dir(class)
使用類的字典屬性:class._ _ dict _ _#這裡會返回一個字典,
3、一些特殊的類屬性:

C.__name__ #類C的名字(字串)
C.__doc__ #類C的文件字串
C.__bases__ #類C的所有父類構成的元組
C.__dict__ #類C的屬性
C.__module__ #類C定義所在的模組(1.5 版本新增)
C.__class__ 例項C對應的類(僅新式類中)#注意這裡指的是例項

4、類定義所在模組
類定義在所執行的檔案中是,這時模組名為__main__,

classA.py:
      class Classname:
          pass
      instance=ClassName()
      print(type(instance))
輸出:<class '__main__.ClassName'>

----------

classB.py
     from classA import Classname
     instance=Classname()
     print(type(instance))
輸出:<class 'classA.ClassName'>