靜態屬性:
既可以訪問例項屬性也可以訪問類屬性(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=width
7 self.length=length
8 self.height=height
9 @property
10 def area_room(self):
11 print('%s住的%s房間的面積是%s' %(self.name,self.owner,self.width*self.length))
12 return self.length*self.width
13 r1=room('大樹','501',3,8,5)
14 r2=room('果果','502',10,10,5)
15 # print('%s住的%s房間面積是%s' %(r1.name,r1.owner,r1.width*r1.length))
16 # r1.area_room()
17 # r2.area_room()
18 19 #封裝屬性
20 print(r1.area_room)
21 print(r2.area_room)
22 print(r1.name)
23 print(r2.name)
類方法:
@classmethod 引數預設為cls-->類 可以訪問類屬性
# -------------------------類方法:資料屬性和函式屬性---------------------
# 呼叫時不與任何例項**
# 類級別的操作 與例項無關 不能訪問例項屬性
class room:
tag=1
def __init__(self,r_numb,owner,length,width,heigh):
self.r_numb=r_numb
self.owner=owner
self.length=length
self.width=width
self.heigh=heigh
@classmethod#類方法加classmethod
def tell_info(cls):
print('this is a test')
print(cls.tag)
room.tell_info()#類呼叫自己的方法 self引數問題
靜態方法:
@staticmethod 不能訪問類屬性和例項屬性
# -----------------------靜態方法--------------------
#class room:
def __init__(self,name,owner,width,length,height):
self.name=name
self.owner=owner
self.width=width
self.length=length
self.height=height
@property
def area_room(self):
return self.length * self.width
@classmethod # 類方法加classmethod
def tell_info(cls):
print('this is a test')
print(cls.tag)
# 靜態方法:類的工具包 不與類、例項繫結,不能使用類變數和例項變數
@staticmethod
def bathe():
print('洗澡')
#test()函式無意義
def test(x,y):#例項沒辦法呼叫此函式 r1.test(1,2)
print(x+y)
# print(room.__dict__)
# r1=room('102','大樹',10,3,4)
room.bathe()
收藏 靜態屬性 類方法 靜態方法
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,他可以封裝你寫的邏輯,然後讓使用者呼叫的時候完全感知不到在呼叫後端的什麼邏輯 class shuichi def init self,chang,kuan,gao self.chang chang self.kuan kuan self...
靜態屬性靜態方法
靜態屬性用於儲存內的公有資料 靜態方法裡面只能訪問靜態屬性 靜態成員不需要例項化就可以訪問 類的內部可以通過self或者static關鍵字訪問自身的靜態成員 子內方法中可以通過parent關鍵字訪問父類的靜態成員 可以通過類的名稱在類定義外部訪問靜態成員 class human class nbap...