的 classmethod()
是Python中的內置函數,它為給定函數返回類方法。
用法: classmethod(function)
參數:該函數接受函數名稱作為參數。
返回類型:該函數返回轉換後的類方法。
classmethod()
方法綁定到類而不是對象。類方法可以同時由類和對象調用。這些方法可以通過類或對象來調用。下麵的示例清楚地說明了上麵。
範例1:
# Python program to understand classmethod
class Student:
# creating a variable
name = "Geeksforgeeks"
# creating a function
def print_name(obj):
print("The name is:", obj.name)
# creating print_name classmethod
# before creating this line print_name()
# can be called only with object not with class
Student.print_name = classmethod(Student.print_name)
# now this method can be call as classmethod
# print_name() method is called as class method
Student.print_name()
輸出:
The name is: Geeksforgeeks
範例2:
# Python program to understand classmethod
class Subject:
# creating a variable
favorite_subject = "Networking"
# creating a function
def favorite_subject_name(obj):
print("My favorite_subject_name is:",
obj.favorite_subject)
# creating favorite_subject_name classmethod
# before creating this line favorite_subject_name()
# can be called only with object not with class
Subject.favorite_subject_name = classmethod(Subject.favorite_subject_name)
# now this method can be call as classmethod
# favorite_subject_name() method is called as class method
Subject.favorite_subject_name()
輸出:
My favorite_subject_name is: Networking
classmethod()的使用classmethod()函數用於工廠設計模式,在該模式下,我們想使用類名而不是對象來調用許多函數。
的@classmethod
裝飾器:
的@classmethod
裝飾器,是一個內置的函數裝飾器,它是一個表達式,在定義函數後會對其求值。評估的結果使您的函數定義變得模糊。類方法將類作為隱式第一個參數接收,就像實例方法接收實例一樣。
用法:
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
....
fun: function that needs to be converted into a class method
returns: a class method for function.
- 類方法是綁定到類而不是類對象的方法。
- 他們可以訪問類的狀態,因為它需要一個指向該類而不是對象實例的類參數。
- 它可以修改適用於該類所有實例的類狀態。例如,它可以修改將適用於所有實例的類變量。
在下麵的示例中,我們使用staticmethod()
和classmethod()
檢查一個人是否成年。
# Python program to demonstrate
# use of class method and static method.
from datetime import date
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# a class method to create a
# Person object by birth year.
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)
# a static method to check if a
# Person is adult or not.
@staticmethod
def isAdult(age):
return age > 18
person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)
print (person1.age)
print (person2.age)
# print the result
print (Person.isAdult(22))
輸出:
21 22 True
相關用法
注:本文由純淨天空篩選整理自ankit15697大神的英文原創作品 classmethod() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。