# method 方法
# staticmathod 靜態(tài)的方法 ***
# classmethod 類方法 ****
# 類的操作行為
class Goods:
__discount = 0.8
def __init__(self,name,price):
self.name = name
self.__price = price
@property
def price(self):
return self.__price * Goods.__discount
@classmethod # 把一個方法 變成一個類中的方法,這個方法就直接可以被類調(diào)用,不需要依托任何對象
def change_discount(cls,new_discount): # 修改折扣
cls.__discount = new_discount
apple = Goods('蘋果',5)
print(apple.price)
Goods.change_discount(0.5) # Goods.change_discount(Goods)
print(apple.price)
# 當(dāng)這個方法的操作只涉及靜態(tài)屬性的時候 就應(yīng)該使用classmethod來裝飾這個方法
class Login:
def __init__(self,name,password):
self.name = name
self.pwd = password
def login(self):pass
@staticmethod
def get_usr_pwd(): # 靜態(tài)方法
usr = input('用戶名 :')
pwd = input('密碼 :')
Login(usr,pwd)
Login.get_usr_pwd()
# 在完全面向?qū)ο蟮某绦蛑校?
# 如果一個函數(shù) 既和對象沒有關(guān)系 也和類沒有關(guān)系 那么就用staticmethod將這個函數(shù)變成一個靜態(tài)方法
# 類方法和靜態(tài)方法 都是類調(diào)用的
# 對象可以調(diào)用類方法和靜態(tài)方法么? 可以 一般情況下 推薦用類名調(diào)用
# 類方法 有一個默認(rèn)參數(shù) cls 代表這個類 cls
# 靜態(tài)方法 沒有默認(rèn)的參數(shù) 就象函數(shù)一樣
# 面向?qū)ο蟮倪M(jìn)階
# 網(wǎng)絡(luò)編程
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
