self.attribute_name
. Если нужно узнать, какие атрибуты доступны, можно использовать super().__dir__()
или dir(self)
в дочернем классе.
Чтобы определить атрибуты родительского класса в дочернем классе в Python, можно использовать несколько способов:
.
). Это, однако, не рекомендуется, так как нарушает принципы инкапсуляции.
class Parent:
public_attribute = "Parent Attribute"
class Child(Parent):
def display_parent_attribute(self):
print(Parent.public_attribute) # доступ к атрибуту родителя
child = Child()
child.display_parent_attribute() # Output: Parent Attribute
self
(если это атрибуты экземпляра) или через имя класса (если это атрибуты класса).
class Parent:
class_attribute = "Parent Class Attribute"
def __init__(self, instance_attribute):
self.instance_attribute = instance_attribute
class Child(Parent):
def display_attributes(self):
print(f"Class attribute from Parent: {Child.class_attribute}") # или Parent.class_attribute
print(f"Instance attribute from Parent: {self.instance_attribute}")
child = Child("Child Instance Attribute")
child.display_attributes()
# Output:
# Class attribute from Parent: Parent Class Attribute
# Instance attribute from Parent: Child Instance Attribute
super()
(для методов):super()
. Это особенно полезно при переопределении методов (method overriding) и инициализации объектов.
class Parent:
def __init__(self, name):
self.name = name
def display_name(self):
print(f"Parent's name: {self.name}")
class Child(Parent):
def __init__(self, name, child_attribute):
super().__init__(name) # вызываем __init__ родителя для инициализации name
self.child_attribute = child_attribute
def display_attributes(self):
super().display_name() # вызываем метод display_name родителя
print(f"Child's attribute: {self.child_attribute}")
child = Child("Alice", "Some Value")
child.display_attributes()
# Output:
# Parent's name: Alice
# Child's attribute: Some Value
Важно: super()
обеспечивает правильную инициализацию унаследованных атрибутов и обработку множественного наследования.
__dict__
(не рекомендуется для обычного использования):__dict__
(который является словарем). Однако это менее читаемый и менее гибкий способ, и его следует избегать, если есть другие варианты.
class Parent:
class_attribute = "Parent Class Attribute"
def __init__(self, instance_attribute):
self.instance_attribute = instance_attribute
class Child(Parent):
def display_parent_attributes(self):
print(Parent.__dict__.get('class_attribute')) # или self.__class__.__base__.__dict__.get('class_attribute')
print(self.__dict__.get('instance_attribute'))
child = Child("Child Instance Attribute")
child.display_parent_attributes()
# Output:
# Parent Class Attribute
# Child Instance Attribute
class Parent:
attribute1 = "Value 1"
class Child(Parent):
def get_parent_attribute(self, attribute_name):
return getattr(Parent, attribute_name, None)
child = Child()
print(child.get_parent_attribute("attribute1")) # Output: Value 1
print(child.get_parent_attribute("non_existent_attribute")) # Output: None
Рекомендации:
super()
для доступа к атрибутам и методам родительского класса. Это обеспечивает наиболее чистый, поддерживаемый и расширяемый код.
__dict__
следует использовать только в крайних случаях, когда другие подходы не подходят.