通常要調用一個類的方法,我們需要首先創建該類的一個實例或對象。但是類方法綁定到類,而不是它的對象,所以類方法函數的創建返回給定函數的類方法
**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/zh-hk/n/126969.html