我正在制作类似但功能不同的类,具体取决于类的用途。
class Cup:
def __init__(self, content):
self.content = content
def spill(self):
print(f"The {self.content} was spilled.")
def drink(self):
print(f"You drank the {self.content}.")
Coffee = Cup("coffee")
Coffee.spill()
> The coffee was spilled.
然而,在对象的初始化过程中知道杯子是否会溢出或饮用。如果有很多杯子,则不需要所有杯子都具有这两种功能,因为只会使用其中一个。如何在初始化期间添加函数?
直觉上应该是这样的,但这显然不起作用:
def spill(self):
print(f"The {self.content} was spilled.")
class Cup:
def __init__(self, content, function):
self.content = content
self.function = function
Coffee = Cup("coffee", spill)
Coffee.function()
> The coffee was spilled
如果您在 Python 中使用方法创建一个类,例如
class A
def method(self, param1, param)
它将确保当您调用A().method(x,y)
它时self
用 A 的实例填充参数。当您尝试在 之外自己指定方法时,class
您还必须确保绑定正确完成。
import functools
class Cup:
def __init__(self, content, function):
self.content = content
self.function = functools.partial(function, self)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句