[英]PYTHON Add the contents of a string variable to the beginning of a function?
So what I have here is one function, which is in an object: 所以我这里有一个函数,它在一个对象中:
class objectOne:
def funct1(self):
#Do Stuff
And what I would like to do is have it so when I create two instaces of the object: 当我创建对象的两个实例时,我想要做的就是这样做:
dog = objectOne()
cat = objectOne()
When the variable "animal" i have created contains cat, then it would run: 当我创建的变量“animal”包含cat时,它将运行:
cat.funct1()
And when the variable contains dog, then it would run: 当变量包含dog时,它会运行:
dog.funct1()
Any way to do this? 有什么办法吗? Thanks in advance guys. 先谢谢你们。
Ev :D Ev:D
(To clarify: I can't use an if statement here because as I gain more and more different instances of the object, I don't want to have to add stuff, my final code to call the object's function should be something like: (澄清一下:我不能在这里使用if语句,因为当我获得越来越多不同的对象实例时,我不想添加内容,我调用对象函数的最终代码应该是这样的:
animal.funct1()
In which animal is the variable, not an instance of the object. 动物是变量,而不是对象的实例。 Thanks once again guys!) 再次感谢你们!)
Use dictionary . 使用字典 。 Animals will be keys, objects will be items. 动物将成为钥匙,物体将成为物品。
Example: 例:
animals = {}
animals['cat'] = objectOne()
animal = 'cat'
animals[animal].funct1()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.