staticmethod注释在python中有效吗?

时间:2019-06-06 11:15:21

标签: python static-methods

仅类可以调用静态方法。我对吗 ?。我遇到了来自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运算符调用吗?

0 个答案:

没有答案