覆盖python中的类变量? [英] override class variable in python?
问题描述
以下, base_id
和 _id
是一个类变量,在所有子类之间共享。
是否可以将它们分为每个类?
Below, base_id
and _id
is a class variable and shared among all child classes.
Is there a way to separate them into each class?
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
推荐答案
如果您不想像falsetru所建议的那样违反DRY原则,则需要使用元类。我当时想写点东西,但是关于SO的元类已经有很长的描述了,所以检查出来。
If you don't want to violate the DRY principle like falsetru suggests, you'll need to use metaclasses. I was thinking of writing something up, but there's already a good long description of metaclasses on SO, so check it out.
元类,简而言之,让您控制子类的创建。
Metaclasses, in short, let you control subclass creation.
基本上,您需要做的是,在创建 Parent
的子类后,将 _id
成员添加到新创建的子类。
Basically, what you need to do is, upon the creation of a subclass of Parent
, add the _id
member to the newly-created subclass.
这篇关于覆盖python中的类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!