靜態屬性 類方法

2021-09-04 02:31:44 字數 1993 閱讀 4055

之前學過乙個技巧叫裝飾器,有乙個類提供的方法叫property,他可以封裝你寫的邏輯,然後讓使用者呼叫的時候完全感知不到在呼叫後端的什麼邏輯

class

shuichi

:def

__init__

(self,chang,kuan,gao)

: self.chang = chang

self.kuan = kuan

self.gao = gao

@property

defcal_tiji

(self)

:return self.chang * self.kuan * self.gao

p1 = shuichi(2,

3,4)

print

(p1.cal_tiji)

類在呼叫自己的函式屬性時,跟例項**到一塊了,但是如果只想z執行類的方法,就是不跟任何勢力**,只跟類**的方法,叫做類方法

使用@classmethod放在函式開頭的位置,他就會變成乙個專門供類使用的方法

還有乙個東西是@staticmethod,這個東西叫做類的工具包,他既不和例項繫結到一起,也不和類繫結在一起

staticmethod靜態方法只是名義上的歸屬類管理,不能使用類變數和例項變數,是類的工具包

@staticmethod

#類的工具包

defxizao

(a,b,c)

:print

('%s %s %s洗澡呢'

%(a,b,c)

)dog.xizao(

'lele'

,'yibole'

,'qwe'

)#同樣在類的屬性字典中存在

print

(dog.__dict__)

#如果是p1.__dict__中則不存在

總結:

靜態屬性:@property把函式封裝成為資料屬性,在外部在呼叫時不知道內部邏輯

類方法:@classmethod把函式中傳參的self變成cls,除了不能訪問例項的屬性其他都可以

靜態方法:@staticmethod引數不為self也不為cls,不能訪問類屬性也不能訪問實力屬性

class

cat:

egg =

2def

__init__

(self,name,age)

: self.name = name

self.age = age

@property

defjueyu

(self)

:print

('%s在%s時候做了絕育'

%(self.name,self.age)

) @classmethod

deflong_ago

(cls,name)

:print

('%s之前可是有%s個蛋蛋der'

%(name,cls.egg)

) @staticmethod

deftaijian

(name)

:print

('然後%s現在是乙個太監'

%name)

p1 = cat(

'lazyegg'

,'1歲'

)p1.jueyu

cat.long_ago(

'landan'

)cat.taijian(

'lazyball'

)print

(p1.__dict__)

p1.long_ago(

'bate'

)#傳入時必須得填寫name,因為不能使用例項中的name

p1.taijian(

'bate'

)#傳入時必須得填寫name,因為不能使用例項中的name

#p1.jueyu('bate','1歲')#報錯,因為已經有了例項中的引數了

靜態屬性 類方法 靜態方法

靜態屬性 既可以訪問例項屬性也可以訪問類屬性 self 1 靜態屬性 資料屬性 2 class room 3 def init self,name,owner,width,length,height 4 self.name name 5 self.owner owner 6 self.width w...

靜態屬性 類方法 靜態方法

class room tag 1 def init self,name,owner,width,length,heigh self.name name self.width width self.owner owner self.length length self.heigh heigh 既可以訪...

類和物件 靜態屬性 靜態方法

在php中,使用關鍵字 static 修飾成員屬性和成員方法被稱為靜態屬性和靜態方法。靜態屬性和靜態方法不需要在類被例項化的情況下可以直接使用。與普通的成員屬性不同,靜態屬性屬於類本身而不屬於類的任何例項。靜態屬性可以被看做是儲存在類當中的全域性變數,可以在任何地方通過類來訪問它們。由於靜態屬性不受...