简体   繁体   中英

Can I reference a class instance with a variable in Python?

I have a list of class instances and I want to check if a particular instance in is in the list using a variable set at run time.

class Animal():
    def __init__(self, name):
        self.name = name

cat = Animal('cat')
dog = Animal('dog')
fish = Animal('fish')

animals = [cat, dog, fish]

assert dog in animals # True

target = 'dog'
assert target in animals # Error

Can this be done?

dog is an instance of the Animal class.

You could try loop through each of the classes and get the .name and compare like so:

class Animal():
    def __init__(self, name):
        self.name = name

cat = Animal('cat')
dog = Animal('dog')
fish = Animal('fish')

animals = [cat, dog, fish]

assert dog in animals # True

target = 'dog'

for class_obj in animals:
    print(target == class_obj.name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM