Наследование
Правила поиска имен (функций, переменных) в пространстве имен, при наследовании работает по принципу (Local -> Enclosing -> Global -> Builtins)
class Person:
def __init__(self, age):
self.age = age
def print_age(self):
print(f{self.age})
class Student(Person):
...
s = Student(10)
s.print_age()
print(s.__dict__)
# {'age': 10}
print(Student.__dict__)
# {'__module__': '__main__', '__doc__': None}
print(Person.__dict__)
# {'__module__': '__main__', '__init__': <function Person.__init__ at 0x7fe9358f7240>, 'print_age': <function Person.print_age at 0x7fe93596d1c0>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
1234567891011121314151617181920212223
print(Student.__dict__)
- покажет, что переменной age
нет в классе Student, т.к. она определена в классе Person
[!info] Неявное наследование класса
object
Все объекты (классы) которые создаются будут неявно наследоваться от базового класса object - наследоваться необходимые базовые методы (например,__module
,__doc__
и т.д.)
Для проверки цепочки наследования класса, можно воспользоваться встроенной функцией issubclass
:
class One:
...
class Two(One):
...
class Three(Two):
...
issubclasss(Three, One)
# True
123456789101112
Last updated
Was this helpful?