# method 方法
# staticmathod 靜態的方法 ***
# 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 # 把一個方法 變成一個類中的方法,這個方法就直接可以被類調用,不需要依托任何對象
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)
# 當這個方法的操作只涉及靜態屬性的時候 就應該使用classmethod來裝飾這個方法
class Login:
def __init__(self,name,password):
self.name = name
self.pwd = password
def login(self):pass
@staticmethod
def get_usr_pwd(): # 靜態方法
usr = input('用戶名 :')
pwd = input('密碼 :')
Login(usr,pwd)
Login.get_usr_pwd()
# 在完全面向對象的程序中,
# 如果一個函數 既和對象沒有關系 也和類沒有關系 那么就用staticmethod將這個函數變成一個靜態方法
# 類方法和靜態方法 都是類調用的
# 對象可以調用類方法和靜態方法么? 可以 一般情況下 推薦用類名調用
# 類方法 有一個默認參數 cls 代表這個類 cls
# 靜態方法 沒有默認的參數 就象函數一樣
# 面向對象的進階
# 網絡編程
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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