创新互联Python教程:Pythonclassmethod()
通常要调用一个类的方法,我们需要首先创建该类的一个实例或对象。但是类方法绑定到类,而不是它的对象,所以类方法函数的创建返回给定函数的类方法

在网站设计、成都做网站中从网站色彩、结构布局、栏目设置、关键词群组等细微处着手,突出企业的产品/服务/品牌,帮助企业锁定精准用户,提高在线咨询和转化,使成都网站营销成为有效果、有回报的无锡营销推广。创新互联专业成都网站建设10年了,客户满意度97.8%,欢迎成都创新互联客户联系。
**classmethod(function)** #where function is an name of function
classmethod()参数:
classmethod()函数只接受一个参数
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 函数 | 要转换为类方法的函数 | 需要 |
classmethod()返回值
方法的返回值或输出是类方法,可以在没有类实例的情况下调用。
| 投入 | 返回值 | | 功能 | 返回传递函数的类方法 |
Python 中classmethod()方法的示例
示例 1:如何创建类方法?
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 示例 2:如何使用类方法创建工厂方法?
# 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 示例 3:类方法如何用于继承?
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 本文名称:创新互联Python教程:Pythonclassmethod()
网页网址:http://www.jxjierui.cn/article/cdhheep.html


咨询
建站咨询
