查看: 908| 回复: 4
跳转到指定楼层
上一主题 下一主题
收起左侧

[学Python/Perl] 请教: 关于python类的私有变量访问

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
就是类中带有双下滑线的变量, 一般在类的外部(比如instantiate的一个instance)是不能访问的, 但lz记得以前在网上看到过一个trick, 用myclass.__dict__可以查看类中定义的所有变量, 然后对私有变量用类似于myclass.__private_var==100之类的格式就可以给私有变量附值了, 结论就是python其实对类中私有变量不能提供很好的保护, 但是lz今天在jupyter上又试验了一下这种方法未果, 难道是python的新版本修复了这个漏洞? 还是不一样的编译器处理方式不一样? 多谢!

class chair:
    def __init__(self, weight, height, color):
        self.__weight=weight
        self.__height=height
        self.color=color
    def print_appear(self):
        print("the weight and height of the chair is {}, {}".format(self.__weight, self.__height))
    def __set_weight(self, weight):
        self.__weight=weight
        print("changed the weight!")
        print("new weight is: {}".format(self.__weight))
    def change_appear(self, weight=None, height=None):
        self.__set_weight(weight)

my_chair=chair(20, 100, 'green')
my_chair.print_appear()
chair.__dict__
chair.__weight==50

################
#output:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-20-ccd32a6c32a9> in <module>
----> 1 chair.__weight==50

AttributeError: type object 'chair' has no attribute '__weight'


上一篇:搜索可以既有公司tag 又有topic 分类吗
下一篇:周赛总很快做出3题,做不出第四题,该如何提高?
🔗
striges1111 2020-5-19 01:10:43 | 只看该作者
全局:
"__weight" 不是 "chair" 这个class的member,是“my_chair”这个instance的member
回复

使用道具 举报

🔗
 楼主| fasionfans 2020-5-19 01:19:48 | 只看该作者
全局:
本帖最后由 fasionfans 于 2020-5-19 01:22 编辑
striges1111 发表于 2020-5-19 01:10
"__weight" 不是 "chair" 这个class的member,是“my_chair”这个instance的member

然而用“my_chair.__weight==50“并不会改变my_chair.__weight这个变量的值:my_chair.__weight=50

my_chair.print_appear()
the weight and height of the chair is 20, 100
回复

使用道具 举报

🔗
striges1111 2020-5-19 01:28:37 | 只看该作者
全局:
对,因为__weight不叫这个名字,my_chair.__weight给my_chair增加了一个叫__weight的member,这个member一开始就不存在
https://docs.python.org/3/tutorial/classes.html#tut-private
TL;DR
private __varname == _class__varname
回复

使用道具 举报

全局:
楼上说的对 name mangling了
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表