Reputation: 95
Suppose I have this code:
class abc():
def __init__(self):
self.a = 0
def somefunc(var):
pass
if __name__ == "__main__":
aaa = abc()
somefunc(aaa.a)
Now my question, there is a way to get an instance of the class (aaa) by his attribute (a) that passed to "somefunc" if I have only the attribute? In other words, to move from attribute to his class.
I know that is not popular to do that but I have some situation that forces me to.
Thank you for help!!!!
Upvotes: 0
Views: 314
Reputation: 61
You can use instance as a parameter.
class abc():
def __init__(self, num):
self.a = num
def somefunc(var):
print(var.a)
if __name__ == "__main__":
aaa = abc(2)
somefunc(aaa)
bbb = abc(4)
somefunc(bbb)
Upvotes: 0
Reputation: 629
You can if you really want to, but I wouldn't advise it.
class abc():
def __init__(self,a):
self.a = a
def somefunc(value):
vars_dict = globals() # swap this for whatever dictionary of variables you wish to use
abcs = [vars_dict[i] for i in vars_dict if isinstance(vars_dict[i],abc)]
return [instance for instance in abcs if instance.a == value]
if __name__ == "__main__":
instance1 = abc(1)
instance2 = abc(2)
instance3 = abc(1)
print('1s: {}'.format(str(somefunc(1))))
print('2s: {}'.format(str(somefunc(2))))
print('3s: {}'.format(str(somefunc(3))))
This grabs from vars_dict
all instances with which instance.a == value
. I've implemented the globals() dict here, but you can swap it out for another dictionary as is appropriate.
Enjoy!
Upvotes: 0
Reputation: 39404
The answer is no.
Suppose I have this code:
class abc():
def __init__(self):
self.a = []
def somefunc(var):
pass
if __name__ == "__main__":
aaa = abc()
bbb = abc()
bbb.a = aaa.a
somefunc(aaa.a)
Now should somefunc determine that it should refer to aaa or bbb?
Upvotes: 2