覆盖python中的类变量? [英] override class variable in python?

查看:67
本文介绍了覆盖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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆