在面向?qū)ο蟮某绦蛟O(shè)計模式中,使用類來區(qū)分具有相似屬性的對象。
類的定義和使用
使用class關(guān)鍵字來聲明一個類:
class test:
name='try'
def apple(self):
print('this is apple')
print('hello')
輸出: hello
1.類中可以有任意python代碼,這些代碼在類定義階段便會執(zhí)行
2.因而會產(chǎn)生新的名稱空間,用來存放類的變量名與函數(shù)名,可以通過OldboyStudent.dict查看
3.對于經(jīng)典類來說我們可以通過該字典操作類名稱空間的名字(新式類有限制),但python為我們提供專門的.語法
4.點是訪問屬性的語法,類中定義的名字,都是類的屬性
類的信息的信息會保存在字典中:
class test:
name='try'
def apple(self):
print('this is apple')
print('hello')
res=test.__dict__
print(res)
輸出: {'module': 'main', 'name': 'try', 'apple': <function test.apple at 0x0000001E2265DF28>, 'dict': <attribute 'dict' of 'test' objects>, 'weakref': <attribute 'weakref' of 'test' objects>, 'doc': None}
對類進行操作:
class test:
name='try'
def apple(self):
print('this is apple')
print('hello')
test.age=18 # 添加變量
test.name='Hero' # 修改
del test.name # 刪除
print(test.age)
res=test.__dict__
print(res)
對象
類的實例化,得到對象:
obj1=test()
需要先添加__init__初始化對象:
class test:
def __init__(self,name,age,sex): # 初始化對象的參數(shù)
self.name=name
self.age=age
self.sex=sex
def apple(self):
print('this is apple')
obj1=test('aa',11,'male')
print(obj1.__dict__)
obj1.apple()
輸出結(jié)果:
{'name': 'aa', 'age': 11, 'sex': 'male'}
this is apple
調(diào)用過程是先調(diào)用類生成一個空對象,然后通過調(diào)用test.init初始化對象的值。對象也支持與類相似的增刪改的操作。
屬性查找
類的數(shù)據(jù)屬性共享給對象使用,在內(nèi)存中的ID是一樣的。
類的函數(shù)屬性是綁定給對象用的。
class test:
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def apple(self):
print('this apple for %s' %self.name)
s1=test('tom',12,'male')
s2=test('lucy',15,'female')
s3=test('divd',16,'male')
print(test.apple)
print(s1.apple)
print(s2.apple)
print(s3.apple)
輸出的信息:
#類的函數(shù)屬性是綁定給對象使用的,obj.method稱為綁定方法,內(nèi)存地址都不一樣
#ps:id是python的實現(xiàn)機制,并不能真實反映內(nèi)存地址,如果有內(nèi)存地址,還是以內(nèi)存地址為準
<function test.apple at 0x000000D17FCA0048>
<bound method test.apple of <__main__.test object at 0x000000D17FC96940>>
<bound method test.apple of <__main__.test object at 0x000000D17FC96978>>
<bound method test.apple of <__main__.test object at 0x000000D17FC969B0>>
obj.name會先從obj自己的名稱空間里找name,找不到則去類中找,類也找不到就找父類...最后都找不到就拋出異常。
調(diào)用對象對類的屬性賦值,改變的只是當前對象的屬性值,對類的屬性不產(chǎn)生影響,如果類自身調(diào)用屬性值,并作修改,則屬于此類中所有對象的屬性都會發(fā)生更改。
類中定義的函數(shù)(沒有被任何裝飾器裝飾的),其實主要是給對象使用的,而且是綁定到對象的,雖然所有對象指向的都是相同的功能,但是綁定到不同的對象就是不同的綁定方法
強調(diào):綁定到對象的方法的特殊之處在于,綁定給誰就由誰來調(diào)用,誰來調(diào)用,就會將‘誰’本身當做第一個參數(shù)傳給方法,即自動傳值(方法init也是一樣的道理)
s1.apple() #等同于test.apple(s1)
s2.apple() #等同于test.apple(s2)
s3.apple() #等同于test.apple(s3)
注意:綁定到對象的方法的這種自動傳值的特征,決定了在類中定義的函數(shù)都要默認寫一個參數(shù)self,self可以是任意名字,但是約定俗成地寫出self。
python中一切皆為對象,且python3中類與類型是一個概念,類型就是類.
python為類內(nèi)置的特殊屬性
類名.name# 類的名字(字符串)
類名.doc # 類的文檔字符串
類名.base# 類的第一個父類
類名.bases# 類所有父類構(gòu)成的元組
類名.dict# 類的字典屬性
類名.module# 類定義所在的模塊
類名.class# 實例對應(yīng)的類(僅新式類中)