简体   繁体   English

在python的父类函数中使用子类的类级别属性

[英]Using class level attributes of a subclass in a parent class function in python

How can I change the respective class level attributes using the function of the base class without overloading the function? 如何在不重载函数的情况下使用基类的功能更改相应的类级别属性?

class A:
    a = 0

    def addOne(self):
        print(A.a)      # prints 0
        A.a = A.a + 1
        print(A.a)      # it stores the value of a over all the child classes

class B(A):
    a = 0
    print(A.a)      # prints 0
    print(B.a)      # prints 0
    self.addOne()
    print(A.a)      # prints 1
    print(B.a)      # prints 0

Class C(A):
    a = 0
    print(A.a)      # prints 1
    print(C.a)      # prints 0
    self.addOne()
    print(A.a)      # prints 2
    print(C.a)      # prints 0

I want Ba = 1 and Ca = 1 after self.addOne() . 我想在self.addOne()之后self.addOne() Ba = 1并且Ca = 1

I don't want to use instance attributes as I will have to overload the addOne function for all the child classes. 我不想使用实例属性,因为我必须为所有子类重载addOne函数。

Option 1: Use the type function to get the class of self . 选项1:使用type函数获取self的类。

def addOne(self):
    cls = type(self)
    cls.a += 1

Option 2: Turn addOne into a classmethod : 选项2:addOne转换为classmethod

@classmethod
def addOne(cls):
    cls.a += 1

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

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