【问题标题】:How can I use a Python Class attribute as a default value for a @Classmethod?如何使用 Python 类属性作为 @Classmethod 的默认值?
【发布时间】:2019-10-21 11:50:23
【问题描述】:

看看下面的代码。

我想在类方法my_method() 的声明中使用a 的值作为参数c 的默认值。

我该怎么做?下面的例子失败了。

>>> 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

【问题讨论】:

  • 在那个范围内它只是a。但是,这真的是你想要的吗?因为它不会随着class属性而改变,也就是说,如果你改变X.a,那么默认为my_method仍然是'hello'
  • 一种方法。将c 的默认值设置为None,如果cNone,则在函数体中分配c = X.aexample

标签: python class-method class-attributes


【解决方案1】:

这真的取决于你想要什么,但得到你想要的东西的一种方法就是这样做。

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()

None设为默认,并在函数体中检查None,如果发现是None,则赋值给c。如果您曾经希望 None 成为该函数的有效参数,那么它不会起作用,但这似乎不太可能。

这个习惯用法在 python 中经常被用来避免可变默认参数的陷阱,但在这里它延迟了从 X.a 的赋值直到 X 被实际定义之后。

这也意味着如果您更改X.a,那么my_method 将获得新值。你可能想要也可能不想要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多