Python setattr() function is used to set a value to the object's attribute. It takes three arguments an object, a string, and an arbitrary value, and returns none. It is helpful when we want to add a new attribute to an object and set a value to it. The signature of the function is given below.
Methods are attributes. Everything in Python is objects, really, with methods and functions and anything with a __call__() method being callable objects. They are all objects that respond to the () call expression syntax. Attributes then, are objects found by attribute lookup on other objects.
Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key. Syntax : getattr(obj, key, def) Parameters : obj : The object whose attributes need to be processed.
I'm wondering if it is possible to use setattr to set an attribute to a method within a class like so because when I try I get an error which is going to be shown after the code:
class Test:
def getString(self, var):
setattr(self.getString, "string", var)
return self.getString
test = Test()
test.getString("myString").string
Which errors AttributeError: 'method' object has no attribute 'string'
so I tried it without putting .string
and just tried test.getString("myString")
Same error, but then I tried it without the using the class just like this
def getString(var):
setattr(getString, "string", var)
return getString
getString("myString").string
It returned "myString" like I wanted it to, so how would I do this within a class and why does it work outside of one but inside of one?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With