如何将实例成员的默认参数值传递给方法?

Yug*_*dle 53 python instance-variables default-arguments

我想使用实例的属性值将默认参数传递给实例方法:

class C:
    def __init__(self, format):
        self.format = format

    def process(self, formatting=self.format):
        print(formatting)
Run Code Online (Sandbox Code Playgroud)

尝试时,我收到以下错误消息:

NameError: name 'self' is not defined
Run Code Online (Sandbox Code Playgroud)

我希望该方法的行为如下:

C("abc").process()       # prints "abc"
C("abc").process("xyz")  # prints "xyz"
Run Code Online (Sandbox Code Playgroud)

这里有什么问题,为什么这不起作用?我怎么能做这个工作?

Ada*_*ner 67

您无法将此定义为默认值,因为在定义任何实例之前定义方法时会计算默认值.一个简单的解决方法是做这样的事情:

class C:
    def __init__(self, format):
        self.format = format

    def process(self, formatting=None):
        if formatting is None:
            formatting = self.format
        print(formatting)
Run Code Online (Sandbox Code Playgroud)

self.format如果将只用于formattingNone.


要演示默认值的工作方式,请参阅此示例:

def mk_default():
    print("mk_default has been called!")

def myfun(foo=mk_default()):
    print("myfun has been called.")

print("about to test functions")
myfun("testing")
myfun("testing again")
Run Code Online (Sandbox Code Playgroud)

这里的输出:

mk_default has been called!
about to test functions
myfun has been called.
myfun has been called.
Run Code Online (Sandbox Code Playgroud)

注意如何mk_default只调用一次,这发生在函数被调用之前!

  • 请注意,如果`formatting`是一个假值,例如0,`formatting = formatting或self.format`会将`formatting`设置为`self.format`.这只是咬我.更安全的方法是键入`formatting = formatting如果格式不是其他self.format`或等效的. (2认同)

Kar*_*tel 8

在Python中,名字self不是特别的.它只是参数名称的约定,这就是为什么有一个self参数__init__.(实际上,__init__也不是很特别,特别是它实际上并没有创建对象......这是一个更长的故事)

C("abc").process()创建一个C实例,processC类中查找方法,并以C实例作为第一个参数调用该方法.因此,self如果您提供参数,它将最终出现在参数中.

但是,即使您拥有该参数,也不会允许您编写类似的内容def process(self, formatting = self.formatting),因为self在您设置默认值时尚未在范围内.在Python中,参数的默认值是在编译函数时计算的,并且"卡在"函数中.(这就是为什么,如果您使用默认值[],该列表将记住对函数的调用之间的更改.)

我怎么能做这个工作?

传统方法是None默认使用,检查该值并在函数内替换它.您可能会发现为此目的创建一个特殊值(一个object实例就是您所需要的,只要您隐藏它以便调用代码不使用相同的实例)而不是None.无论哪种方式,你应该检查这个值is,而不是==.


a_g*_*est 6

由于您想用作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('custom')  # Doesn't work!
c.process(formatting='custom')
Run Code Online (Sandbox Code Playgroud)

请注意,使用这种方法,您只能通过关键字传递相应的参数,因为如果您通过位置提供它,这会在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')
Run Code Online (Sandbox Code Playgroud)

这还允许按位置传递参数,但是方法解析顺序变得不那么明显(例如,这可能会影响 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')
Run Code Online (Sandbox Code Playgroud)