如何在子类中访问父类的私有变量?
时间: 2025-06-15 11:23:26 浏览: 10
在 Python 中,父类的私有变量(使用双下划线 `__` 前缀声明)是不直接可访问的,这是为了防止无意中的修改。然而,如果你真的需要从子类访问这些变量,可以通过以下几种方式:
1. **继承属性(_ClassName__private_variable)**:
子类可以直接使用 `self.__class__.__name__ + '__' + private_variable_name` 的形式来获取父类的私有变量。虽然这不是官方推荐的方法,但可以在某些特殊情况下使用。
```python
class Parent:
def __init__(self):
self.__private_var = 'parent_value'
class Child(Parent):
def access_parent_private(self):
parent_class_name = self.__class__.__name__
print(getattr(parent_class_name, '__' + 'private_var', None))
# 使用时
child = Child()
child.access_parent_private() # 输出: parent_value
```
2. **属性魔术方法(__getattr__ 和 __getattribute__)**:
另一种方法是在父类中定义 `__getattr__` 或 `__getattribute__` 魔术方法,当尝试访问不存在的属性时,它们会被调用。你可以在这里检查并提供私有变量的值给子类。
```python
class Parent:
def __init__(self):
self.__private_var = 'parent_value'
def __getattr__(self, attr):
if attr.startswith('__') and not attr.endswith("__"):
return super().__getattribute__(attr)
if attr == "__private_var":
return "Parent's private var"
raise AttributeError(f"{type(self).__name__!r} object has no attribute {attr!r}")
class Child(Parent):
pass
child = Child()
print(child.private_var) # 输出: Parent's private var
```
但是,请注意,这种做法可能破坏封装原则,因为通常不建议让子类暴露对父类内部细节的直接访问。
阅读全文
相关推荐


















