Статический метод должен вызываться только классом.Я прав ?.Я наткнулся на приведенный ниже фрагмент от 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
?