[英]Can I pass a function as a class attribute and call it?
我实际上可以使用另一个类的函数作为类实例/对象的参数和属性吗?
我注意到如果我做这样的事情会有很多奇怪的地方(请注意,我使用的是 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() 一样。
您可以将函数作为参数传递:
def foo():
print('hello')
def bar(_f):
_f()
bar(_f=foo)
'hello'
请注意,当您将()
添加到函数名称时,您将调用它。 要作为参数传递,您只需要名称,而不是调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.