首页 / PYTHON / 团体访问python超类属性
团体访问python超类属性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了团体访问python超类属性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2050字,纯文字阅读大概需要3分钟。
内容图文
![团体访问python超类属性](/upload/InfoBanner/zyjiaocheng/690/603739a5cf8440ae925ad2a15595b30c.jpg)
这个问题已经在这里有了答案: > Python method name with double-underscore is overridden? 2个
我有两个课程,大致采用以下形式:
class Foo:
def __init__(self, foo):
self.__foo = foo
class Bar(Foo):
def bar(self):
print self.__foo
当我尝试在Bar实例上调用bar方法时,它失败.
b = Bar('foobar')
b.bar()
结果:
Traceback (most recent call last):
File "foobar.py", line 14, in <module>
b.bar()
File "foobar.py", line 10, in bar
print self.__foo
AttributeError: Bar instance has no attribute '_Bar__foo'
我的理解是,该代码应基于two other问题进行工作,为什么不呢?
解决方法:
简单. __foo在开头包含2个下划线,因此假定它是类私有方法,并且已转换为_Classname__method.
当您请求访问在Bar对象上这样命名的属性时,它将询问Bar类是否具有此方法(不是Foo类),因此self .__ foo始终与self._Bar__foo相同.
When an identifier that textually occurs in a class definition begins
with two or more underscore characters and does not end in two or more
underscores, it is considered a private name of that class. Private
names are transformed to a longer form before code is generated for
them. The transformation inserts the class name, with leading
underscores removed and a single underscore inserted, in front of the
name. For example, the identifier __spam occurring in a class named
Ham will be transformed to _Ham__spam.
如果您稍微修改代码
class Foo:
def __init__(self, foo):
self.__foo = foo
assert hasattr(self, '_Foo__foo'), 'Attribute has been just created'
class Bar(Foo):
def bar(self):
assert hasattr(self, '_Foo__foo'), 'No errors, thanks to inheritance'
assert语句不会导致任何AssertionErrors.
将__getattribute__方法添加到Bar类以捕获对Bar对象的所有请求:
class Bar(Foo):
def bar(self):
print('Accessing __foo from bar')
print(self.__foo)
def __getattribute__(self, name):
print('Requested', name)
return super().__getattribute__(name)
b = Bar('foobar')
b.bar()
输出中将有3行(除AttributeError之外):
Requested bar
Accessing __foo from bar
Requested _Bar__foo # AttributeError follows
如您所见,如果您请求的属性有2个下划线,则Python会即时对其进行重命名.
内容总结
以上是互联网集市为您收集整理的团体访问python超类属性全部内容,希望文章能够帮你解决团体访问python超类属性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。