仅类可以调用静态方法。我对吗 ?。我遇到了来自geeksforgeeks的以下片段。
from datetime import date
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# a class method to create a Person object by birth year.
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)
# a static method to check if a Person is adult or not.
@staticmethod
def isAdult(age):
return age > 18
# can a method annotated with staticmethod be called through self
def IsAdultorNot(self):
return self.isAdult(age)
person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)
print(person1.age)
print(person2.age)
# print the result
# the below statement should raise an error isn't it ?.
print(person2.isAdult(22))
出于好奇,我尝试使用类的实例和类本身调用用staticmethod注释的方法。令人惊讶的是,我从两种方式都得到了结果。
通过对象调用静态函数时会出现错误吗?而isAdult
是静态方法,可以通过self
运算符调用吗?