我可以将函数作为类属性传递并调用它吗?

时间:2020-01-16 19:34:04

标签: python class oop

我可以实际使用另一个类的函数作为类实​​例/对象的参数和属性吗?

我注意到,如果我做这样的事情,会有很多奇怪的地方(请注意,我使用Jupyter实验室):

class ObjectClass:
    #A class; I will insert a function into generalMethod
    def __init__(self, generalMethod):
        self.generalMethod = generalMethod

class GeneralMethods():    
    #Two different methods that I want to call
    def method1(self):
        add(2)
    def method2(self):
        print("Hey now, you're an all-star, get your game on, go play" )
        return "Hey, I can return stuff, at least!",2

def add(input):
    #A simple function that adds 1 to input
    print(1 + input)

#Creating two objects with different methods as inputs from GeneralMethods
gm = GeneralMethods()
object1 = ObjectClass(gm.method1())
object2 = ObjectClass(gm.method2())

#Attempting to call anything from generalMethod; a getter method does the same
object1.generalMethod
object2.generalMethod

gm.method1()gm.method2()在其中做的所有事情,甚至当我简单地将其声明为对象/实例的参数时

但是anyObject.generalMethod不会做任何事情除了会在我调用返回时返回任何内容,并且如果有函数存在,它将返回None

所以我真的可以从属性调用函数,并且从属性(anyObjectIChoose.generalMethod调用函数时,它的性能就像gm.method1()一样。

1 个答案:

答案 0 :(得分:1)

您可以将函数作为参数传递

def foo():
    print('hello')

def bar(_f):
    _f()

bar(_f=foo)
'hello'

请注意,在函数名称中添加()时,将调用它。要作为参数传递,您只需要名称,而无需调用它。

相关问题