Search code examples
pythonpython-3.9

Can we assign instance attributes in __new__?


For example if we do like:

class blah(object):
    def __new__(self, **attr):
        try: self.isBlah = attr["true_or_false"]
    def __init__(self, **attr):
        if self.isBlah:
             self.blah = self.isBlah
a = blah(true_or_false=True)
print(a.blah)

I know that __new__ one starts first, but can we assign value to it? Because when I do it on Python interpreter, it does not, but in website compilers, it does.


Solution

  • Yes, it's possible. The first argument passed to __new__ is the class to create an instance of. So in order to do what you want the class instance must first be created — then you can add attributes to that before returning it.

    Below is an example of doing that based on the code in your question. Note that when writing Python code it's usually best to follow the PEP 8 - Style Guide for Python Code — particularly the Naming conventions.

    class Class:
        def __new__(cls, **kwargs):
            attr = kwargs.get('true_or_false', False)
            inst = super().__new__(cls)
            inst.is_blah = attr
            return inst
    
        def __init__(self, **kwargs):
            if self.is_blah:
                self.blah = self.is_blah
    
    
    c = Class(true_or_false=True)
    print(c.blah)  # -> True