-
@property讓類函數(shù)能像類變量一樣操作。 -
@classmothod類函數(shù),屬于整個類,類似于C++/JAVA中的靜態(tài)函數(shù)。類方法有類變量cls傳入,從而可以用cls做一些相關的處理。子類繼承時,調用該類方法時,傳入的類變量cls是子類,而非父類。既可以在類內部使用self訪問,也可以通過實例、類名訪問。即在類的函數(shù)前加@classmethod屬性,函數(shù)第一個參數(shù)為cls類,表示該函數(shù)是類的方法,而不需要綁定具體實例。
在類方法里面可以調用類的屬性,并且在類調用該函數(shù)時,會將自身作為第一個參數(shù)傳入,類方法不能訪問實例。實例可以調用類方法。 -
@staticmethod將外部函數(shù)集成到類體中,既可以在類內部使用self訪問,也可以通過實例、類名訪問?;旧系韧谝粋€全局函數(shù)。 - 使用@staticmethod或@classmethod,就可以不需要實例化,直接類名.方法名()來調用。這有利于組織代碼,把某些應該屬于某個類的函數(shù)給放到那個類里去,同時有利于命名空間的整潔。
- staticmethod基本沒用只是為了整合到class里面方便使用
A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.
- 目的是為了直接使用類就可以調用這個方法,不用實例化才能調用。
A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how dict.fromkeys(), a classmethod, returns an instance of the subclass when called on a subclass:
class room:
tag=1
def __init__(self, name,length,width,height):
self.name=name
self.length=length
self.width=width
self.height=height
@property #通過類提供的property對求面積的函數(shù)進行封裝
def square(self):
s=self.length*self.width
print('%s的面積為%s'%(self.name,s))
@classmethod
def volumn(cls,length,width,height): #第一個參數(shù)為cls,即類
v=length*width*height
print('訪問類的屬性%s'%cls.tag) #類方法可以訪問類的屬性
print('類%s的體積為%s'%(cls,v))
@staticmethod
def haha(x,y): #靜態(tài)方法既沒有類cls參數(shù),也沒有實例self參數(shù),因此不能訪問類和實例的屬性
print('From staticmethod,%s and %s is haha'%(x,y))
def hahahaha(x,y): #可以這樣定義普通方法,但不建議這樣使用,沒有意義
print('From common method,%s and %s is hahahaha' % (x, y))
room1=room('room1',10,13,3)
room1.square #直接調用求面積的函數(shù)方法就可以執(zhí)行函數(shù),而不需要加()
room.volumn(10,13,3) #類調用類方法時,將類自身作為第一個參數(shù)傳入
room.haha('Jane','Alan')
room.hahahaha('Jane','Alan')
# 執(zhí)行結果:
# room1的面積為130
# 訪問類的屬性1
# 類<class '__main__.room'>的體積為390
# From staticmethod,Jane and Alan is haha
# From common method,Jane and Alan is haha
-
@classmothod和staticmethod的區(qū)別:staticmethod不需要表示自身對象的self和自身類的cls參數(shù),就跟使用函數(shù)一樣。 -
classmethod必須使用類對象作為第一個參數(shù),而staticmethod則可以不傳遞任何參數(shù)。 - 例子
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()
A.static_foo()
A.class_foo()