裝飾類方法和靜態方法

2021-09-10 02:10:15 字數 929 閱讀 5450

裝飾類方法或靜態方法是很簡單的,不過要確保裝飾器在 @classmethod 或 @staticmethod 之前。

import time

from functools import wraps

def timethis(func):

@wraps(func)

start = time.time()

r = func(*args, **kwargs)

end = time.time()

print(end - start)

return r

class spam:

@timethis

def instance_method(self, n):

print(self, n)

while n > 0:

n -= 1

@classmethod

@timethis

def class_method(cls, n):

print(cls, n)

while n > 0:

n -= 1

@staticmethod

@timethis

def static_method(n):

print(n)

while n > 0:

n -= 1

s = spam()

s.instance_method(1000000)

spam.class_method(1000000)

spam.static_method(1000000)

@classmethod 和 @staticmethod 實際上並不會建立可直接呼叫的物件, 而是建立特殊的描述器物件。因此當你試著在其他裝飾器中將它們當做函式來使用時就會出錯。 確保這種裝飾器出現在裝飾器鏈中的第乙個位置可以修復這個問題。

類方法和靜態方法

通過靜態方法和類方法能夠把相關的函式封裝到乙個類裡面,有效的將 組織起來,提高 的可維護性 class date object def init self,year,month,day self.year year self.month month self.day day 普通方法 def ech...

例項方法 類方法和靜態方法

1 例項方法,即需要通過建立例項 物件 進行呼叫的方法。下方即為例項方法的例子 class person object def init self self.name zs self.age 10 p person print p.name,p.age 2 類方法,即在定義方法時使用 classme...

類方法 例項方法和靜態方法

例項方法 類方法 靜態方法三種方法在記憶體中都屬於類,區別在於呼叫方式不同 例項方法 定義 第乙個引數必須是例項物件,該引數名一般約定為 self 通過它來傳遞例項的屬性和方法 也可以傳類的屬性和方法 呼叫 只能由例項物件呼叫。例項物件可以呼叫例項方法 類方法和靜態方法類方法 定義 使用裝飾器 cl...