由于您想使用
self.format
作为默认参数,这意味着该方法需要是实例特定的(即在类级别无法定义)。相反,您可以在类的
__init__
中定义特定的方法。这是您可以访问实例特定属性的位置。
一种方法是使用
functools.partial
来获取更新的(特定)版本的方法:
from functools import partial
class C:
def __init__(self, format):
self.format = format
self.process = partial(self.process, formatting=self.format)
def process(self, formatting):
print(formatting)
c = C('default')
c.process()
c.process(formatting='custom')
请注意,使用此方法时,您只能通过关键字传递相应的参数,如果您按位置提供它,则会在“partial”中创建冲突。
另一种方法是在“__init__”中定义并设置该方法:
from types import MethodType
class C:
def __init__(self, format):
self.format = format
def process(self, formatting=self.format):
print(formatting)
self.process = MethodType(process, self)
c = C('test')
c.process()
c.process('custom')
c.process(formatting='custom')
这样也可以通过位置传递参数,但方法解析顺序变得不太明显(这可能会影响IDE检查,但我想有特定的IDE解决方法)。
另一种方法是为这些“实例属性默认值”创建自定义类型,并使用特殊装饰器执行相应的
getattr
参数填充。
import inspect
class Attribute:
def __init__(self, name):
self.name = name
def decorator(method):
signature = inspect.signature(method)
def wrapper(self, *args, **kwargs):
bound = signature.bind(*((self,) + args), **kwargs)
bound.apply_defaults()
bound.arguments.update({k: getattr(self, v.name) for k, v in bound.arguments.items()
if isinstance(v, Attribute)})
return method(*bound.args, **bound.kwargs)
return wrapper
class C:
def __init__(self, format):
self.format = format
@decorator
def process(self, formatting=Attribute('format')):
print(formatting)
c = C('test')
c.process()
c.process('custom')
c.process(formatting='custom')
process method
中编辑self
的错误。 - Yugal Jindle=>
而不是=
来实现这一点。目前计划在Python 3.12中推出。 - Karl Knechtel