Alp*_*ket 2 methods inheritance attributes parent python-3.x
无法在父方法中调用子属性,测试如下:
#!/usr/bin/env python3
class A():
def getPath(self):
return self.__path
class B(A):
def __init__( self, name, path):
self.__name = name
self.__path = path
instance = B('test', '/home/test/Projects')
print(instance.getPath())
Run Code Online (Sandbox Code Playgroud)
运行 python 测试文件$ ./test.py返回
./test.py
Traceback (most recent call last):
File "./test.py", line 17, in <module>
print(instance.getPath())
File "./test.py", line 6, in getPath
return self.__path
AttributeError: 'B' object has no attribute '_A__path'
Run Code Online (Sandbox Code Playgroud)
小智 5
您收到此消息是因为您使用的是私有属性。如果您使用非私有属性来执行此操作,则会成功。
Python 中的私有属性旨在允许每个类拥有自己的变量私有副本,而该变量不会被子类覆盖。因此,在 B 中,__path 表示 _B__path,在 A 中,__path 表示 __A_path。这正是 Python 的工作原理。 https://docs.python.org/3/tutorial/classes.html#tut-private
由于希望 A 能够访问 __path,因此不应使用双下划线。相反,您可以使用单个下划线,这是一种约定,表示变量是私有的,而无需实际强制执行。
#!/usr/bin/env python3
class A():
def getPath(self):
return self._path
class B(A):
def __init__( self, name, path):
self.__name = name
self._path = path
instance = B('test', '/home/test/Projects')
print(instance.getPath())
$ ./test.py
/home/test/Projects
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4200 次 |
| 最近记录: |