1. 程式人生 > >面向對象和類

面向對象和類

position span elf pre nes 傳參 sim ims bsp

#!/usr/bin/python #-*-coding:utf-8 -*- #!/usr/bin/python #-*-coding:utf-8 -*- # class 類名: # ‘‘‘文檔註釋‘‘‘ # 類體 #類 特征+技能 類是一系列對象的特征(變量)和技能(函數)的結合體 # class chinese: # country=‘china‘ # jiguan=‘haihai‘ # def talk(self): #這個self 是要傳入參數的 否則報錯 # print(‘talking‘,self) # # p=chinese() # print(p) #類 在定義節點 運行就會執行 不用專門執行
#類的兩種用法 #1.屬性的引用 #2.實例化 #1.屬性的引用 # print(chinese.country) #china # print(chinese.talk) #內存地址 # chinese.talk(123) ##類調用函數 就得傳參數 # ##增加修改屬性 # chinese.x=1 # print(chinese.x) # chinese.country=‘jianada‘ # print(chinese.country) # print(chinese.jiguan) # del chinese.jiguan #刪除屬性 # print(chinese.jiguan)
#2.實例化 #類() 就是類的實例化,得到的是一個具體的對象 # p1=chinese() # print(p1) # ‘‘‘ # <__main__.chinese object at 0x000002528CD6D7F0> # ‘‘‘ ‘‘‘ 對象只有一種,就是屬性引用 ‘‘‘ # p1=chinese() # print(p1) # print(p1.country) #china # p2=chinese() # print(p2) # print(p2.country) #china #對象有共同的特征,也有各自不同的特征,以下是類裏定義 共同特征 不同特征
#__init__ # class chinese: # country=‘china‘ # def __init__(self,name,age,sex,): #定義不同 name age sex # self.Name=name #self.大小寫都可以 p1.Name=name # self.Age=age #p1.Age=age # self.Sex=sex #p1.Sex=sex # def talk(self): # print(‘talkint‘,self.Name) #self.Name 可以看到具體是誰調用的 # # # p1=chinese() # print(p1) ‘‘‘ TypeError: __init__() missing 3 required positional arguments: ‘name‘, ‘age‘, and ‘sex‘ ‘‘‘ ‘‘‘ 解釋: def __init__(self,name,age,sex,): 這裏有4個參數 但是報錯三個參數沒有傳 因為會把對象作為參數傳給self p1=chinese() 比如這個就會把p1作為參數傳給self # ‘‘‘ # p1=chinese(‘agon‘,‘18‘,‘male‘) # print(p1) # print(p1.country) # print(p1.Name) # print(p1.Age) # print(p1.talk()) #對象直接調用 又把自己作為參數傳進去了 # # ‘‘‘ # <__main__.chinese object at 0x000002BC683DD9B0> # china # agon # 18 # # ‘‘‘ ‘‘‘ 類與對象的名稱空間以及綁定方法 ‘‘‘ class chinese: country=‘china‘ def __init__(self,name,age,sex,): #定義不同 name age sex self.Name=name #self.大小寫都可以 p1.Name=name self.Age=age #p1.Age=age self.Sex=sex #p1.Sex=sex def talk(self): print(‘talkint‘,self.Name) #self.Name 可以看到具體是誰調用的 p1=chinese(‘qiqi‘,‘22‘,‘male‘) # print(p1) p2=chinese(‘nini‘,‘22‘,‘male‘) print(chinese.__dict__) #查看chinese的內置名稱空間 ‘‘‘ 字典的格式 {‘__module__‘: ‘__main__‘, ‘country‘: ‘china‘, ‘__init__‘: <function chinese.__init__ at 0x00000257E4E9EF28>, ‘talk‘: <function chinese.talk at 0x00000257E4EA3048>, ‘__dict__‘: <attribute ‘__dict__‘ of ‘chinese‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘chinese‘ objects>, ‘__doc__‘: None} ‘‘‘ print(p1.__dict__) ‘‘‘ {‘Name‘: ‘qiqi‘, ‘Age‘: ‘22‘, ‘Sex‘: ‘male‘} ‘‘‘ print(p1.country) #先去自己的__dict__裏找,沒有再去類裏找 再沒有就沒了 print(id(p1.country)) #查看id print(id(p2.country)) #查看id ‘‘‘ id 一樣 因為是共同的屬性 1879109063152 1879109063152 ‘‘‘ print(chinese.talk) print(p1.talk) #查看id print(p2.talk) #查看id ‘‘‘ 長得並不一樣 雖然是共同屬性 但是talkself傳入的是對象本身 對象不同 最後結果不同 <function chinese.talk at 0x000002C6104D3048> <bound method chinese.talk of <__main__.chinese object at 0x000002C6104CD198>> <bound method chinese.talk of <__main__.chinese object at 0x000002C6104CDAC8>> ‘‘‘

面向對象和類