i have this code:
def some_method():
#i need to get some attrs :(
return 'blabla'
setattr(parent, 'new_attr', some_method)
it’s there a way to get other attributes of the parent inside the some_method function?
Thanks in advance!
Update: (solution)
I solved in this way, i don’t know if the best.
def some_method(parent):
# print or do something parent.xy_attribute
return 'blabla'
parent.new_attr = some_method(parent)
and it works!
Thanks again!
If
parentwere a class, then you can access its attributes like you would with any other method of a class, by giving the self parameter and using that.If it isn’t a class, perhaps the best way to handle this would be to write your function within a wrapper/factory/something instead of as a method directly.
You can then use
parent.new_attr()and it’ll be able to print/manipulate/whatever any parent attributes you want.Here’s a more fleshed out example of how you might use this to manipulate a counter on a function (or, say, flush a function cache).