簡體   English   中英

從派生類重新綁定基類中的不可變類屬性

[英]Rebinding immutable class attribute in the base class from a derived class

我在python中有這個通用問題。 基類定義一個類屬性class_attr 此屬性是不可變的,在這種情況下,它是一個數字。 我想從派生類中更改此屬性,從而將Base.class_attr重新綁定到新值(在我的玩具箱中,將其遞增)。

問題是如何在不顯式命名Base.class_attr += 1 Base情況下執行此操作。

class Base(object):
    # class attribute: 
    class_attr = 0

class Derived(Base): 
    @classmethod
    def increment_class_attr(cls):        
        Base.class_attr += 1 
        # is there a solution which does not name the owner of the 
        # class_attr explicitly?

        # This would cause the definition of Derived.class_attr, 
        # thus Base.class_attr and Derived.class_attr would be 
        # two independent attributes, no more in sync:
    #   cls.class_attr += 1

Derived.increment_class_attr()
Derived.increment_class_attr()

print Base.class_attr # 2

請注意 :我很想問這個問題,也就是我可以重新綁定父類的屬性嗎? 我沒有解決此問題的解決方法(例如,將increment_class_attr移至Base)。

使用__bases__屬性:

In [68]: class Base(object):
    ...:     # class attribute: 
    ...:     class_attr = 0
    ...:     

In [69]: class Derived(Base):
    ...:     @classmethod
    ...:     def inc(cls):
    ...:         p, = cls.__bases__
    ...:         p.class_attr += 1
    ...:         

In [70]: Base.class_attr
Out[70]: 0

In [71]: Derived.inc()

In [72]: Derived.inc()

In [73]: Base.class_attr
Out[73]: 2

如果您有多個繼承:

In [88]: class DifferentInherited(object):
    ...:     class2_attr = 0
    ...: 


In [90]: class Der2(Base, DifferentInherited):
    ...:     @classmethod
    ...:     def inc(cls):
    ...:         print cls.__bases__
    ...:         a, b, = cls.__bases__
    ...:         print a.class_attr
    ...:         print b.class2_attr
    ...:         

In [91]: Der2.inc()
(<class '__main__.Base'>, <class '__main__.DifferentInherited'>)
2
0

假設您也不知道繼承順序,則需要測試每個類的變量:

In [127]: class Der3(DifferentInherited, Base):
     ...:     @classmethod
     ...:     def inc(cls):
     ...:         # This gets a list of *all* classes with the attribute `class_attr`
     ...:         classes = [c for c in cls.__bases__ if 'class_attr' in c.__dict__]
     ...:         for c in classes:
     ...:             c.class_attr += 1
     ...:             

In [128]: Der3.inc()

In [129]: Base.class_attr
Out[129]: 3

In [131]: DifferentInherited.class2_attr
Out[131]: 0

多重繼承使用__mro__

In [146]: class Multi(Der3):
     ...:     @classmethod
     ...:     def inc(cls):
     ...:         c_attr =  [c for c in cls.__mro__ if 'class_attr' in c.__dict__]
     ...:         print c_attr
     ...:         c_attr[0].class_attr += 1
     ...:         

In [147]: Multi.inc()
[<class '__main__.Base'>]

In [148]: Base.class_attr
Out[148]: 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM