Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a custom object attribute

I was messing around with inherited classes and wondered if it was possible to set a custom object attribute using a method. It would work something like this:

class MyClass(object):
    def __init__(self):
        super.__init__()
    def setCustAttr(self, name, value):
        #...
g=MyClass()
g.setCustAttr("var",5)
g.var+=6
g.var="text"
  • Is there any way to do this?
  • Could you use exec("self."+string+"="+value)?
like image 928
Mutantoe Avatar asked Aug 29 '26 00:08

Mutantoe


1 Answers

This is what the setattr function does:

setattr(g, 'var', 5)
# g.var is now 5
like image 196
user2357112 supports Monica Avatar answered Aug 31 '26 13:08

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!