Methods 在Python中的_uinit__;()中添加方法

Methods 在Python中的_uinit__;()中添加方法,methods,python-3.6,Methods,Python 3.6,我正在创建类似的类,但是根据类的使用,具有不同的函数 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}.") Coffe

我正在创建类似的类,但是根据类的使用,具有不同的函数

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)
时,它会用A的实例填充
self
参数。当您尝试在
类之外指定自己的方法时,您还必须确保绑定正确完成

import functools
class Cup:
    def __init__(self, content, function):
        self.content = content
        self.function = functools.partial(function, self)