Home > OS >  Instance method to return name of attribute to which it assigns a value
Instance method to return name of attribute to which it assigns a value

Time:10-19

Any way to return name of instance attribute in method it calls on assignment?

class MyClass:
    def __init__(self):
        self.not_relevant = 0
        self.name_to_return = self.assign_own_name()
    
    def assign_own_name(self):
        return "name_to_return"  # to replace 

assert MyClass().name_to_return == 'name_to_return'

Use case: multiple attribute are initialized and value supplying instance method operates on basis of attribute name.

    def __init__(self):
        self.name_1 = do('name_1')
        ...
        self.name_n = do('name_n')
    
    def do(self, x):
        return x  # e.g. db query

CodePudding user response:

If you override the setattr dunder method, you can do it like this:

class Class:
    def __init__(self):
        pass
    def __setattr__(self, name, value):
        super(Class, self).__setattr__(name, value)
        return name

_class = Class()

print(_class.__setattr__('foo', 'bar'))
print(_class.foo)

Output:

foo
bar

Whilst...

_class.foo = 'bar'

...would still be syntactically correct you can't get the return value from such an assignment. If assignment expressions (walrus operator) worked with attributes then it would be easy but that's not allowed

  • Related