Если родительский класс изменяет атрибут, а дочерний класс переопределяет этот атрибут, то поведение зависит от того, как именно родительский класс изменяет атрибут и как дочерний класс его переопределил.
Основные сценарии:
class Parent:
attribute = "parent_value"
def change_attribute(self):
self.attribute = "parent_changed"
class Child(Parent):
attribute = "child_value"
parent = Parent()
child = Child()
print(parent.attribute) # Output: parent_value
print(child.attribute) # Output: child_value
parent.change_attribute()
print(parent.attribute) # Output: parent_changed
print(child.attribute) # Output: child_value (значение не изменилось)
class Parent:
class_attribute = "parent_class_value"
def change_class_attribute(self):
Parent.class_attribute = "parent_class_changed"
class Child(Parent):
class_attribute = "child_class_value"
parent = Parent()
child = Child()
print(parent.class_attribute) # Output: parent_class_value
print(child.class_attribute) # Output: child_class_value
parent.change_class_attribute()
print(parent.class_attribute) # Output: parent_class_changed
print(child.class_attribute) # Output: child_class_value
class Parent:
def __init__(self):
self._attribute = "parent_value" # Используем инкапсуляцию
def get_attribute(self):
return self._attribute
def set_attribute(self, value):
self._attribute = value
class Child(Parent):
def __init__(self):
super().__init__()
self._attribute = "child_value" # Переопределяем в дочернем классе
def get_attribute(self):
return "Child's attribute: " + self._attribute
parent = Parent()
child = Child()
print(parent.get_attribute()) # Output: parent_value
print(child.get_attribute()) # Output: Child's attribute: child_value
parent.set_attribute("new_parent_value")
print(parent.get_attribute()) # Output: new_parent_value
print(child.get_attribute()) # Output: Child's attribute: child_value
Ключевые моменты:
super()
позволяет дочернему классу вызывать методы родительского класса, обеспечивая возможность расширения функциональности вместо полной замены.Важно понимать эти механизмы, чтобы избегать неожиданного поведения и корректно реализовывать наследование в Python.