python - python 中类方法和静态变量的行为

标签 python inheritance class-method static-variables

假设我有以下类(class)

class Parent: 
    message = "Hello World"
    @classmethod
    def print_message(cls):
        print(cls.message)
    @classmethod 
    def change_message(cls, new_message):
            cls.message =  new_message

class Child_one(Parent):
    @classmethod 
    def print_messsage(cls):
        print (cls.message)
    @classmethod 
    def change_message(cls, new_message):
        cls.message = new_message

class Child_two(Parent):
    @classmethod
    def print_message(cls):
        print(cls.message)

我想我的问题是子类的 cls 指的是什么,因为如果我更改父类中的静态变量 message ,它会正确地更改两个子项中的消息

Parent.change_message("This is new message")
Child_one.print_message() # This is new message 
Child_two.print_message() # This is new message

这是我预期的行为,两个cls.message都引用父类的消息。然而这样做

Child_one.change_message("I am child one") 

导致诸如以下行为

Parent.print_message() # This is new message 
Child_one.print_message() # I am child one 
Child_two.print_message() # This is new message 

因此Child_one的cls.message变量不再指向父类的消息。

在其他语言中,例如 c++c# static,更改父类或子类的静态变量会导致所有父类和派生类发生更改。有没有办法在 python 中复制这种行为,如果没有为什么不呢?

最佳答案

写入后:

一旦您将某个内容分配给类或对象的成员,而该成员的名称不存在,则会创建该成员。

事实上,成员的名称出现在基类中并不会改变任何东西。它是在类本身中创建的。

阅读后:

名称解析如下:首先尝试在类本身中查找成员,然后在其基类中查找成员。

关于python - python 中类方法和静态变量的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58888652/

相关文章:

C++:方法中的字符串成员别名

Python:检查Twitter用户A是否关注用户B

python - 用与另一个数组的零相对应的零替换元素的快速方法

python - 如何终止由 Python subprocess.Popen() 创建的进程

java - Horse 对象继承

objective-c - 伪装成 Class 的 NSProxy 在 64 位运行时不处理 respondsToSelector

python - 在带注释的文本上使用 NLTK 方法,例如 tokenize

java - 如何在子类中访问父类(super class)的 protected 方法?

c# - 如何将 List<Child> 传递给带有参数 List<Parent> 的方法?

java - 类方法继承