python - 在python中覆盖类变量?

标签 python class

下面,base_id_id是一个类变量,在所有子类之间共享。
有没有办法将它们分成每个类?

from itertools import count

class Parent(object):
    base_id = 0
    _id = count(0)

    def __init__(self):
        self.id = self.base_id + self._id.next()


class Child1(Parent):
    base_id = 100
    def __init__(self):
        Parent.__init__(self)
        print 'Child1:', self.id

class Child2(Parent):
    base_id = 200
    def __init__(self):
        Parent.__init__(self)
        print 'Child2:', self.id

c1 = Child1()                   # 100
c2 = Child2()                   # 201 <- want this to be 200
c1 = Child1()                   # 102 <- want this to be 101
c2 = Child2()                   # 203 <- want this to be 201

最佳答案

如果你真的需要这样使用ID,使用参数:

class Parent(object):
    def __init__(self, id):
        self.id = id

class Child1(Parent):
    _id_counter = count(0)
    def __init__(self):
        Parent.__init__(self, 100 + self._id_counter.next())
        print 'Child1:', self.id

等等

这假设您不会直接构造 Parent 的实例,但是对于您的示例代码来说这看起来是合理的。

关于python - 在python中覆盖类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19719767/

相关文章:

python - 如何在 mac 10.7.5 上正确安装 matplotlib?还有为什么Anaconda安装成功后找不到命令 "conda"呢?

python - 如何用插值拟合 ODE 系统?

javascript - 将 onclick 分配给整个类(class)

java - “找不到或加载主类”是什么意思?

python -> "operator"用于定义函数

python - 从 2D 直方图引用数据

javascript - 试图从数组中检索对象的颜色

ios - 从不同的类 Swift 访问 uibutton Action

c++ - 从类中打印变量

python - 不允许迭代 tf.Tensor : AutoGraph is disabled in this function