Python - 将不同类的对象传递给函数

标签 python class object dictionary

我在 python 中的类和对象方面遇到了一些问题。我有两个类,并且我实例化了每个类的一个对象。当用户键入某个字符串时,我想将这些对象传递到函数中。然后该函数将调用它所采用的对象的类方法。 (每个类的方法具有相同的名称)。我在下面制作了一个示例文件:

    class Test1(object):

       def method1(self):
          print("test1")

    class Test2(object):

       def method1(self):
          print("test2")


    def Call(something):
       return something.method1

    def Call2(something):
       y = input("> ")
       return something.method1

    array = [Test1(), Test2()]
    my_dict = {'call': Call(array[0]), 'call2': Call2(array[1])}


    x = input("> ")

    if x in my_dict:
       my_dict[x]()

我认为发生的是 Call2() 在运行时被调用并请求输入。然后第二个 input() 被调用。有人可以解释为什么即使 if 语句没有机会评估字符串也会运行 Call2() 吗?可能有很多事情我都误解了。如有任何帮助,我们将不胜感激。

编辑:好的,我知道这些函数是在字典声明期间调用的。您将如何将函数链接到字典,同时仍将对象传递给它?

最佳答案

Q: Could someone explain why Call2() runs even when the if statement doesn't get a chance to evaluate a string?

您在此处调用这两个函数:

my_dict = {'call': Call(array[0]), 'call2': Call2(array[1])}

Q: How would you go about linking a function to the dict while still passing the object to it?

通常所做的是提供彼此分开的函数和参数。这是一个例子:

>>> def the_caller(f, args=()):
...     return f(*args)
... 
>>> def present_me(name):
...     return 'My name is ' + name
... 
>>> the_caller(present_me, args=('Rik',))
'My name is Rik'

您的示例代码设计得太糟糕,无法构建有意义的东西。

关于Python - 将不同类的对象传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10237717/

相关文章:

python - 如何教初学者在 Python 中反转字符串?

python - 加快深度的 numpy 整数数组索引

python - Python 3.5 上的文档图像去扭曲脚本

typescript 错误 : An outer value of 'this' is shadowed by this container

C++ 使用变量访问类的公共(public)成员

带参数的Python子类化过程

javascript - ES6 中的多级对象解构

python - 如何在Python Mockito中正确使用verifyNoUnwantedInteractions()?

javascript - 聚合物 2.0 类遗传保护特性

java - 实例和对象之间的功能区别是什么?