在 Python 中的 __init__() 中添加方法
Adding methods in __init__() in Python
我正在制作 classes,它们相似,但功能不同,具体取决于 class 的用途。
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
class A
def method(self, param1, param)
它将确保当您调用 A().method(x,y)
时它会用 A 的实例填充 self
参数。当您尝试在 class
之外自己指定方法时,您必须还要确保绑定正确完成。
import functools
class Cup:
def __init__(self, content, function):
self.content = content
self.function = functools.partial(function, self)
我正在制作 classes,它们相似,但功能不同,具体取决于 class 的用途。
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 中创建 classclass A
def method(self, param1, param)
它将确保当您调用 A().method(x,y)
时它会用 A 的实例填充 self
参数。当您尝试在 class
之外自己指定方法时,您必须还要确保绑定正确完成。
import functools
class Cup:
def __init__(self, content, function):
self.content = content
self.function = functools.partial(function, self)