Python classmethod()

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

 **classmethod(function)** #where function is an name of function

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 

原创文章,作者:HCFYS,如若转载,请注明出处:https://www.506064.com/n/126969.html

(0)
HCFYSHCFYS
上一篇 2024-10-03
下一篇 2024-10-03

相关推荐

发表回复

登录后才能评论