Python:按值查找类的实例 [英] Python: Find Instance of a class by value
问题描述
我创建了一个类的很多实例.然后我想通过它的名字找到一个实例.但我收到错误消息 TypeError: get() missing 1 required positional argument: 'value'
.
i created much instances of a class. Then I want to find one instance by its name. But I get the error message TypeError: get() missing 1 required positional argument: 'value'
.
class Test(object):
def __init__(self, value):
self.value = value
def get(self, value):
if self.value == value:
return self
else:
return None
test_obj = Test('foobar')
print(test_obj.value)
instance = Test.get('foobar')
if instance:
print(instance.value)
推荐答案
再次重新阅读您的问题,我认为到目前为止我们所有人都没有抓住重点.您想检查 Test
类的所有实例以查看实例是否具有值 'foobar'
(在本例中为 test_obj
.参考此答案,您可以像这样修改代码:
Re-reading your question again, I think all of us have missed the point so far. You wanted to check all instances of the class Test
to see if an instance has the value 'foobar'
(in this case, test_obj
. Referencing this answer, you can modify your code like so:
class Test(object):
# class attribute to keep track of class instances
instances = []
def __init__(self, value):
self.value = value
Test.instances.append(self)
# class method to access the get method without any instance
@classmethod
def get(cls, value):
return [inst for inst in cls.instances if inst.value == value]
然后您可以创建多个测试:
You can then create multiple tests:
test1 = Test(1)
test2 = Test(2)
test3 = Test(3)
instance = Test.get(3)
# [<__main__.Test object at 0x03F29CD0>]
instance[0].value
# 3
返回一个list
实例而不是单个实例对我来说是有意义的.但是,如果您只对第一个匹配感兴趣,则可以相应地修改 return
语句.
It makes sense for me to return a list
of instances instead of one single instance. If you however is only interested in the first match, you can modify the return
statement accordingly.
原答案:
instance = Test.get('foobar')
是问题所在.你是通过它的类而不是它的实例来引用 Test
的.所以很自然地,实例方法 .get(self, value)
正在寻找实例的第一个参数 self
.
instance = Test.get('foobar')
is the problem. You're referencing Test
by its class, not its instance. So naturally the instance method .get(self, value)
is looking for the first argument self
for the instance.
通常,如果您已经有一个实例(例如 Test().get('foobar')
),则该实例默认作为 self
传递到实例方法中.
Usually if you already have an instance (e.g. Test().get('foobar')
) then the instance is passed into the instance method as self
by default.
你仍然可以调用实例方法,但你只需要显式地传入实例:
You could still call the instance method, but you just need to explicitly pass the instance in:
Test.get(test, 'foobar')
这篇关于Python:按值查找类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!