python中的class_static的@classmethod的使用 classmethod的使用,主要針對(duì)的是類而不是對(duì)象,在定義類的時(shí)候往往會(huì)定義一些靜態(tài)的私有屬性,但是在使用類的時(shí)候可能會(huì)對(duì)類的私有屬性進(jìn)行修改,但是在沒(méi)有使用class method之前對(duì)于類的屬性的修改只能通過(guò)對(duì)象來(lái)進(jìn)行修改,這是就會(huì)出現(xiàn)一個(gè)問(wèn)題當(dāng)有很多對(duì)象都使用這個(gè)屬性的時(shí)候我們要一個(gè)一個(gè)去修改對(duì)象嗎?答案是不會(huì)出現(xiàn)這么無(wú)腦的程序,這就產(chǎn)生classmethod的妙用。請(qǐng)看下面的代碼:
class Goods:
__discount = 0.8
def __init__(self,name,money):
self.__name = name
self.__money = money
@property
def price(self):
return self.__money*Goods.__discount
@classmethod
def change(cls,new_discount):#注意這里不在是self了,而是cls進(jìn)行替換
cls.__discount = new_discount
apple = Goods('蘋果',5)
print(apple.price)
Goods.change(0.5) #這里就不是使用apple.change()進(jìn)行修改了
print(apple.price)
上面只是簡(jiǎn)單的列舉了class method的一種使用場(chǎng)景,后續(xù)如果有新的會(huì)持續(xù)更新本篇文章 2.既然@staticmethod和@classmethod都可以直接類名.方法名()來(lái)調(diào)用,那他們有什么區(qū)別呢
從它們的使用上來(lái)看,
@staticmethod不需要表示自身對(duì)象的self和自身類的cls參數(shù),就跟使用函數(shù)一樣。
@classmethod也不需要self參數(shù),但第一個(gè)參數(shù)需要是表示自身類的cls參數(shù)。
如果在@staticmethod中要調(diào)用到這個(gè)類的一些屬性方法,只能直接類名.屬性名或類名.方法名。
而@classmethod因?yàn)槌钟衏ls參數(shù),可以來(lái)調(diào)用類的屬性,類的方法,實(shí)例化對(duì)象等,避免硬編碼。
下面上代碼。
class A(object):
bar = 1
def foo(self):
print 'foo'
@staticmethod
def static_foo():
print 'static_foo'
print A.bar
@classmethod
def class_foo(cls):
print 'class_foo'
print cls.bar
cls().foo()
###執(zhí)行
A.static_foo()
A.class_foo()
知識(shí)點(diǎn)擴(kuò)展:python classmethod用法
需求:添加類對(duì)象屬性,在新建具體對(duì)象時(shí)使用該變量
class A():
def __init__(self,name):
self.name = name
self.config = {'batch_size':A.bs}
@classmethod
def set_bs(cls,bs):
cls.bs = bs
def print_config(self):
print (self.config)
A.set_bs(4)
a = A('test')
a.print_config()
以上就是python中的class_static的@classmethod的使用的詳細(xì)內(nèi)容,更多關(guān)于python classmethod使用的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- Python classmethod裝飾器原理及用法解析
- Python 類方法和實(shí)例方法(@classmethod),靜態(tài)方法(@staticmethod)原理與用法分析
- python @classmethod 的使用場(chǎng)合詳解
- 對(duì)Python中的@classmethod用法詳解
- 基于python中staticmethod和classmethod的區(qū)別(詳解)