通常要调用一个类的方法,我们需要首先创建该类的一个实例或对象。但是类方法绑定到类,而不是它的对象,所以类方法函数的创建返回给定函数的类方法
**classmethod(function)** #where function is an name of function
classmethod()
参数:classmethod()
函数只接受一个参数
参数 | 描述 | 必需/可选 |
---|---|---|
函数 | 要转换为类方法的函数 | 需要 |
classmethod()
返回值方法的返回值或输出是类方法,可以在没有类实例的情况下调用。
| 投入 | 返回值 | | 功能 | 返回传递函数的类方法 |
classmethod()
方法的示例 class Products:
getcode = 'P36’
def getProductCode(cls):
print('The Product Code is:', cls.getcode)
# create printCode class method
Products.getProductCode = classmethod(Products .getProductCode )
Products.getProductCode ()
输出:
The Product Code is: P36
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
pers 19)
person.display()
pers 1985)
person1.display()
输出:
Adam's age is: 19
John's age is: 31
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def fromFathersAge(name, fatherAge, fatherPersonAgeDiff):
return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
class Man(Person):
sex = 'Male'
man = Man.fromBirthYear('John', 1985)
print(isinstance(man, Man))
man1 = Man.fromFathersAge('John', 1965, 20)
print(isinstance(man1, Man))
输出:
True
False