gpt4 book ai didi

python - Python中定义类变量时如何引用类方法?

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:17 27 4
gpt4 key购买 nike

我有以下类和类变量:

class MyClass:
class_var_1 = "a"
class_var_2 = run_class_method()

@classmethod
def run_class_method(cls):
return "ran class method"

但是,解释器说 run_class_method 没有定义。使用 MyClass.run_class_method() 也不起作用。来自 java 背景,我不明白为什么这不起作用。那么,我该如何解决呢?

此外,我发现如果我在类的末尾定义类变量,这会起作用。这在 Python 中被认为是不好的做法吗?

最佳答案

python中的类体是一个可执行上下文,不像Java那样只包含声明。这最终意味着执行顺序在类定义中很重要。

引用文档:

class definition is an executable statement.

...

The class’s suite is then executed in a new execution frame (see Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. [4] A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace.

更多 lengthier explanations .

如果你想调用一个函数来定义一个类变量,你可以通过以下方式之一来实现:

  1. 使用静态方法:

    class MyClass:
    def _run_instance_method():
    return "ran instance method"
    run_instance_method = staticmethod(_run_instance_method)

    class_var_1 = "a"
    class_var_2 = _run_instance_method() # or run_instance_method.__func__()
  2. 或将其定义为独立函数:

    def run_method():
    return "ran method"

    class MyClass:
    class_var_1 = "a"
    class_var_2 = run_method()

    # optional
    run_method = staticmethod(run_method)
  3. 或使用 __func__ 访问原始函数并提供一个虚拟 cls 值:

    class MyClass:
    @classmethod
    def run_class_method(cls):
    return "ran class method"

    class_var_1 = "a"
    class_var_2 = run_class_method.__func__(object())
  4. 或者在创建类后设置类变量:

    class MyClass:
    @classmethod
    def run_class_method(cls):
    return "ran class method"

    class_var_1 = "a"

    MyClass.class_var_2 = MyClass.run_class_method()

关于python - Python中定义类变量时如何引用类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54621348/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com