简体   繁体   English

轻松编辑继承类的基类变量

[英]Easily editing base class variables from inherited class

How does communication between base classes and inherited classes work? 基类和继承的类之间的通信如何工作?

I have a data class in my python code ( storing all important values, duh ), I tried inheriting new subclasses from the data base class , everything worked fine except the fact that the classes were not actually communicating ( when one class variable was changed in a subclass, the class attribute was not changed in the base class nor any other subclasses. 我的python代码中有一个数据类(存储所有重要值,duh),我尝试从数据库类继承新的子 ,除类实际上未进行通信(当更改一个类变量时)外,其他一切工作正常一个子类,类属性在基类,也没有任何其它亚类改变。

I guess I just failed to understand how inheritance works, my question is : Does inheritance keep any connection to the base classes, or are the values set at the time of inheritance? 我想我只是无法理解继承的工作原理, 我的问题是 :继承是否与基类保持任何联系,还是在继承时设置了值?

If there is any connection, how do you easily manipulate base class variables from a subclass ( I tried it with the cls variable to access base class variables, didn't work out ) 如果存在任何连接,您如何轻松地从子类中操作基类变量(我尝试使用cls变量来访问基类变量,但没有解决)

Example

class Base:
    x = 'baseclass var' # The value I want to edit

class Subclass(Base):
    @classmethod(cls)
        ???edit_base_x_var_here??? # This is the part I don't know

Well, you could do that in this way: 好吧,您可以通过以下方式做到这一点:

class Base:
    x = 'baseclass var' # The value I want to edit

class Subclass(Base):
    @classmethod
    def change_base_x(cls):
        Base.x = 'nothing'


print Subclass.x
Subclass.change_base_x()
print Subclass.x

furthermore, you don't have to use @classmethod , it could be staticmethod, because you don't need current class object cls : 此外,您不必使用@classmethod ,它可以是staticmethod,因为您不需要当前的类对象cls

class Base:
    x = 'baseclass var' # The value I want to edit

class Subclass(Base):
    @staticmethod
    def change_base_x():
        Base.x = 'nothing'

EDITED: 编辑:

According to your question, about other way. 根据您的问题,关于其他方法。 Yes it is, but not so pretty. 是的,但不是很漂亮。 I would say more. 我会说更多。 If you want to change variable of base class, then you will do it globally though, so that option with assigning to Base.x is the best way you can achieve that. 如果您想更改基类的变量,那么您将在全局范围内进行操作,因此将该选项与Base.x一起分配是实现该目标的最佳方法。

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

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