覆盖python中的类变量?

eug*_*ene 9 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
Run Code Online (Sandbox Code Playgroud)

jpm*_*c26 6

如果您确实需要以这种方式使用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
Run Code Online (Sandbox Code Playgroud)

等等

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


Mik*_*one 4

如果您不想像 falsetru 建议的那样违反 DRY 原则,则需要使用元类。我正在考虑写一些东西,但是SO 上已经有一个关于元类的详细描述,所以请检查一下。

简而言之,元类让您可以控制子类的创建。

基本上,您需要做的是,在创建 的子类后Parent,将该_id成员添加到新创建的子类中。