相关疑难解决方法(0)

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

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

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)

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

python instance-variables default-arguments

53
推荐指数
3
解决办法
3万
查看次数

我可以将类方法和默认参数传递给另一个类方法

我想将类方法作为默认参数传递给另一个类方法,以便我可以将该方法重用为@classmethod:

@classmethod
class foo:
    def func1(self,x):
        do somthing;
    def func2(self, aFunc = self.func1):
        # make some a call to afunc
        afunc(4)
Run Code Online (Sandbox Code Playgroud)

这就是为什么在func2aFunc默认情况下调用该方法的原因self.func1,但是我可以从类外部调用这个相同的函数,并在输入处传递一个不同的函数.

我明白了:

NameError:未定义名称"self"

这是我的设置:

class transmissionLine:  
    def electricalLength(self, l=l0, f=f0, gamma=self.propagationConstant, deg=False):  
Run Code Online (Sandbox Code Playgroud)

但我希望能够electricalLength使用不同的函数调用gamma,例如:

transmissionLine().electricalLength (l, f, gamma=otherFunc)
Run Code Online (Sandbox Code Playgroud)

python class

6
推荐指数
1
解决办法
3506
查看次数