靜態屬性 類方法 靜態方法

2021-09-25 14:56:16 字數 1285 閱讀 9829

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

既可以訪問類自己的屬性也可以訪問例項自己的屬性

@property

defcal_area(self):

#print('%s 住的 %s 總面積是 %s'%(self.owner,self.name,self.width*self.length))

return self.width*self.length

r1=room('

廁所','

alex

',100,100,10000)

#像類一樣訪問自己的屬性,所呼叫的函式不用加()

print(r1.cal_area)

訪問不到例項的屬性,主要是給類用的

@classmethod#

(給類用的)

def tell_info(cls,x):#

cls引數接收的是類名,類名自動傳入第乙個引數

print

(cls)

print('

---->

',cls.tag,x)#

print('---->',room.tag)

#def tell_info(self):

#print('----->',self.tag)

room.tell_info(10)

不能訪問類屬性和例項屬性,只是類的工具包

@staticmethod

defwash_body(a,b,c):

print('

%s %s %s正在洗澡

'%(a,b,c))

room.wash_body(

'alex

','yuanhao

','wupeiqi')

r1=room('

公共廁所

','yuanhao

',1,1,10000)#

例項(物件)只有資料屬性沒有函式屬性(用於調類的函式屬性)

r1.wash_body('

alex

','yuanhao

','wupeiqi

')

靜態屬性 類方法 靜態方法

靜態屬性 既可以訪問例項屬性也可以訪問類屬性 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...

靜態屬性 類方法

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

靜態屬性靜態方法

靜態屬性用於儲存內的公有資料 靜態方法裡面只能訪問靜態屬性 靜態成員不需要例項化就可以訪問 類的內部可以通過self或者static關鍵字訪問自身的靜態成員 子內方法中可以通過parent關鍵字訪問父類的靜態成員 可以通過類的名稱在類定義外部訪問靜態成員 class human class nbap...