0
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.

Sam-gege
  • 723
  • 3
  • 12

2 Answers2

1

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
-2

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
coder.py
  • 1
  • 1