来自变量的Python类信息
在以下代码中:来自变量的Python类信息,python,class,Python,Class,在以下代码中: class species: def __init__(self, continent): self.continent=continent giraffe = species("africa") animal = "giraffe" 编辑:动物是字符串 我可以从var“animal”中检索“africa”吗?访问该属性 动物。大陆是的。animal和giraffe都是对同一底层对象的引用。很像“Jala015”、“Jala Smith”和“妈妈”(
class species:
def __init__(self, continent):
self.continent=continent
giraffe = species("africa")
animal = "giraffe"
编辑:动物是字符串
我可以从var“animal”中检索“africa”吗?访问该属性
动物。大陆是的。
animal
和giraffe
都是对同一底层对象的引用。很像“Jala015”、“Jala Smith”和“妈妈”(或爸爸?)可能都是指同一个人
类似地,如果通过其中一个引用更改对象的大陆
,则该更改将通过另一个引用可见,因为它们都指向相同的位置
更新
现在你说动物不是一个对象的引用,而是一个字符串。有两种方法可以做到这一点,它们都有点复杂
首先,如果giraffe
是全局的(如您的代码所示,它是全局的),那么它将在字典中。您可以这样做:
giraffe = species('Africa')
animal = "giraffe"
continent = globals()[animal].continent
如果giraffe不是全局变量,而是函数中的局部变量,那么这将不起作用。您可能可以使用locals()
获得它,但即使这样也不确定。在这种情况下,一般来说,您应该将这些内容放在自己的字典中进行查找:
Zoo = {} # empty dictionary
giraffe = species('Africa')
Zoo['giraffe'] = giraffe
animal = "giraffe"
continent = Zoo[animal].continent
通过将物种名称存储在Animal
类中,可以简化此操作,因此:
class Animal:
def __init__(self, name, where):
self.name = name
self.continent = where
然后,您可以将对象放入一个deque、dict、list、set、tuple或任何其他您喜欢的东西中,并仍然使用蛮力进行匹配:
animal.continent是您需要的参考资料。请在关于类和对象的教程中查找这些详细信息。可能与我忘记的内容重复:animal=“giraffe”我忘记了:animal=“giraffe”这会改变一切。更新了更多示例。
Zoo = [ Animal('giraffe', 'Africa'), Animal('zebra', 'Africa'), Animal('Cheeto-Stained Ferret-Wearing Shitgibbon', 'North America') ]
pet = None
for animal in Zoo:
if animal.name == 'giraffe':
pet = animal
break