简体   繁体   English

从类方法函数调用变量到普通方法

[英]Calling a variable from a classmethod function to a normal method

I would like to call a variable from a classmethod to a different method inside the same class:我想从一个类方法中调用一个变量到同一个类中的另一个方法:

class A():
    @classmethod
    def b(cls):
        cls.g = 5
    def c(self):
        if self.g < 1:
            print("TestA")
        else:
            print("TestB")

When doing:做的时候:

x = A()
x.c()

I get:我得到:

AttributeError: 'A' object has no attribute 'g'

I've read and searched for a similar case but haven't found one.我已经阅读并搜索了一个类似的案例,但没有找到。 Most deal with calling variables from the init method and that doesn't apply here.大多数处理从 init 方法调用变量,这在这里不适用。

If you don't run .b() beforehand, your .g doesn't exist,...at all.如果您不事先运行.b() ,则您的.g不存在,......根本不存在。

Add an __init__ function to your class and declare .g there to make sure it exists at least.向您的类中添加一个__init__函数并在那里声明.g以确保它至少存在。

You did not define g as a class attribute of the class A .您没有将g定义为类A的类属性。 This could be done this way:这可以通过这种方式完成:

class A():
    g = 7

but then in your code you are treating g as instance ( self.g ) and class variable ( cls.g ) at the same time.但是在您的代码中,您同时将g视为实例( self.g )和类变量( cls.g )。 While this works ( self.g will refer to cls.g ) it may be confusing.虽然这有效( self.g将引用cls.g )它可能会令人困惑。

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

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