创新互联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.hantingmc.com/qtweb/news35/396785.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联