如何在Python中通过内部类获取伪私有属性?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在Python中通过内部类获取伪私有属性?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1124字,纯文字阅读大概需要2分钟。
内容图文
![如何在Python中通过内部类获取伪私有属性?](/upload/InfoBanner/zyjiaocheng/665/b0c6534273fe433882d1286f80aa12ce.jpg)
class Test:
__x = 1
class C:
def test(self):
print(Test.__x)
c = C()
a = Test()
a.c.test()
我收到这样的错误信息
AttributeError: type object ‘Test’ has no attribute ‘_C__x’
那么,是内部阶级无法获得外部阶级的权利吗?
还是可以使用其他技术?
这个问题来自阅读Learning Python,当作者写CardHolder时,一个内部类作为描述符使用instance .__ name到达外部类的属性,那么我们是否可以访问__X属性的规则是什么?
感谢您阅读我的问题.
解决方法:
Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.
class Test:
__x = 1 # <= A
class C:
def test(self):
print(Test.__x) # <= B
c = C()
>在A中,类为Test,因此__x替换为_Test__x,因此,Test实际上具有_Test__x属性
>在B中,类是C,因此__x替换为_C__x,因此您实际访问的属性是Test._C__x
要访问Test类定义之外的Test类的’private’__x属性,您应该使用:Test._Test__x
print(Test._Test__x)
内容总结
以上是互联网集市为您收集整理的如何在Python中通过内部类获取伪私有属性?全部内容,希望文章能够帮你解决如何在Python中通过内部类获取伪私有属性?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。