简体   繁体   English

如何使用Python Class属性作为@Classmethod的默认值?

[英]How can I use a Python Class attribute as a default value for a @Classmethod?

Take a look at the code below. 看一下下面的代码。

I want to use the value of a as the default value for argument c in the declaration of the classmethod my_method() . 我想在类方法my_method()的声明my_method() a的值用作参数c的默认值。

How can I do it? 我该怎么做? The example below fails. 下面的示例失败。

>>> class X:
...     a = 'hello'
...     def __init__(self, b):
...         self.b = b
...     @classmethod
...     def my_method(cls, c=X.a):
...         print 'cls.a = {}'.format(cls.a)
...         print 'c = {}'.format(c)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in X
NameError: name 'X' is not defined

It really depends what you want, but one way to get what you seem to want is to do it like this. 这确实取决于您想要的东西,但是要获得您想要的东西的一种方法就是这样做。

class X:
    a = 'hello'
    def __init__(self, b):
        self.b = b
    @classmethod
    def my_method(cls, c=None):
        if c is None:
            c = X.a
        print('cls.a = {}'.format(cls.a))
        print('c = {}'.format(c))

X.my_method()

Make the default None and check for None in the function body, assigning to c if it is found to be None . 使默认None ,检查None在函数体中,分配给c如果它被发现是None If you ever wanted None to be a valid argument for the function then it wouldn't work, but that doesn't seem likely. 如果您曾经希望None不能用作该函数的有效参数,那么它将不起作用,但这似乎不太可能。

This idiom is often used in python to avoid the pitfalls mutable default argument, but here it delays the assignment from Xa until after X has actually been defined. 这个习惯用法通常在python中使用,以避免陷阱可变的默认参数,但是在这里,它将从Xa的赋值延迟到X实际定义之后。

It also means that if you change Xa then my_method will pick up the new value. 这也意味着,如果您更改Xamy_method将选择新值。 You may or may not want that. 您可能想要也可能不想要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM