Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use the <code>__bases__</code> attribute:</p> <pre><code>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 </code></pre> <p>If you have multiple inheritance:</p> <pre><code>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() (&lt;class '__main__.Base'&gt;, &lt;class '__main__.DifferentInherited'&gt;) 2 0 </code></pre> <p>Assuming you don't know the inheritance order either, you'll need to test each class for the variable:</p> <pre><code>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 </code></pre> <p>And multiple inheritance uses <code>__mro__</code>:</p> <pre><code>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() [&lt;class '__main__.Base'&gt;] In [148]: Base.class_attr Out[148]: 4 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload