Python:操作方法:取决于标志的实例属性,而标志本身就是该实例/对象的属性 [英] Python: How to: attribute of an instance which depends on flag, which is itself an attribute of that instance / object

查看:71
本文介绍了Python:操作方法:取决于标志的实例属性,而标志本身就是该实例/对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下最小示例:

class MyClass:
    a = False
    b = 0
    if a:
        b = 1

MCinst = MyClass()

此处 MCinst 具有两个属性, MCinst.a MCinst.b ,其默认值分别为 False 0 .我尝试使用 if 语句实现的是,当我设置 MCinst.b 的值将自动切换为 1 > MCinst.a = True .但这显然不符合预期,因为 MCinst.b 的值保持为 0 .

Here MCinst has two attributes, MCinst.a and MCinst.b with default values False and 0 respectively. What I was trying to achieve with the if statement, is that the value of MCinst.b would automatically switch to 1 when I set MCinst.a = True. But this obviously does not work as intended, since the value of MCinst.b stays 0.

我知道我可以删除 if 语句,并从外部修改 b ,就像修改 a 一样.但是我仍然很好奇是否有一种方法可以使我想要的工作成为现实.当我更改同一实例的另一个属性时,实例的属性会自动更改.

I know that I could remove the if statement and simply modify b from the outside, in the same way in which I modified a. But I am still curious if there is a way to make work what I wanted—i.e. to have an attribute of an instance change automatically when I change another attribute of the same instance.

推荐答案

class MyClass:
    a = False
    b = 0     

    def __setattr__(self, key, value):
        if key == 'a':
            setattr(self, 'b', 1)
        super().__setattr__(key, value)

如果您确实要更改class属性,则可以使用

If you actually want to change the class attribute, you can use

setattr(self.__class__, 'b', 1)

这篇关于Python:操作方法:取决于标志的实例属性,而标志本身就是该实例/对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆