设置类属性只有在初始化期间创建时才能。

huangapple go评论71阅读模式
英文:

how to set class attribute only if it is created during init

问题

class Foo:
    def __init__(self):
        self.A = 100

class Boo(Foo):
    def __init__(self):
        super(Boo, self).__init__()
        self.B = None


x = Boo()
print(x.A, x.B)

# 100 None

如上所示,我已经创建了一个 Boo 的实例,它具有属性 AB。现在我只想在它们在 __init__ 中创建时才为它们分配值。也就是说,如果我设置 x.A=0,它会起作用,但当我想为一个新属性 x.C=False 分配值时,它不应执行任何操作。

英文:
class Foo:
    def __init__(self):
        self.A = 100

class Boo(Foo):
    def __init__(self):
        super(Boo, self).__init__()
        self.B = None


x = Boo()
print(x.A, x.B)

# 100 None

As shown above, I've created an instance of Boo with attributes A and B. Now I'd like to assign value to attributes only if they are created during __init__. i.e. if I set x.A=0 it will work, but when I want to set value to a new attribute x.C=False it should do nothing.

答案1

得分: 1

Sure, here is the translated code part:

不完全是你所询问的,但你可能想要使用__slots__ 来控制可以创建哪些属性,然后确保它们在 __init__ 中进行初始化。

class Foo:
    __slots__ = ('A',)

    def __init__(self):
        self.A = 100

class Boo(Foo):
    __slots__ = ('B',)

    def __init__(self):
        super().__init__()
        self.B = None

x = Boo()

你可以继续在代码的其他地方修改 x.Ax.B 的值(即使它们没有在 __init__ 中创建),但任何尝试创建新属性,比如 x.C,将导致 AttributeError

英文:

Not quite what you are asking, but you probably want to use __slots__ to control which attributes can be created, then ensure that they are initialized in __init__.

class Foo:
    __slots__ = ('A',)

    def __init__(self):
        self.A = 100


class Boo(Foo):
    __slots__ = ('B',)

    def __init__(self):
        super().__init__()
        self.B = None


x = Boo()

You can continue to modify the values of x.A and x.B elsewhere in the code (even if not created in __init__), but any attempt to create a new attribute like x.C will result in an AttributeError.

答案2

得分: -2

你可以尝试覆盖Boo类的__setattr__()函数,然后可以设置一个条件,使用hasattr()内置函数来检查给定名称的实例是否已存在,如果存在则设置值,否则不做任何操作。以下是可能帮助您的代码:

class Boo(Foo):
    def __init__(self):
        super(Boo, self).__init__()
        self.B = None

    def __setattr__(self, name, value):
        if hasattr(self, name):
            super().__setattr__(name, value)
        else:
            pass  # 或者在找不到实例的情况下执行任何操作
英文:

You may try to override __setattr__() function of Boo class, and then you can set a condition to using hasattr() built-in function to check if the instance is already present with the given name or not, if it is present set the value otherwise do nothing, here is the code that may help you;

class Boo(Foo):
    def __init__(self):
        super(Boo, self).__init__()
        self.B = None
    def __setattr__(self, name, value):
        if hasattr(self, name):
            super().__setattr__(name, value)
        else:
            pass # or anything yo want to do in case instance not found

huangapple
  • 本文由 发表于 2023年4月11日 00:47:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978962.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定