【问题标题】:Python Class Attributes and SubclassingPython 类属性和子类化
【发布时间】:2015-05-22 14:48:45
【问题描述】:

我已经用谷歌搜索并玩了一段时间,但尝试做这样的事情没有结果:

class  A(object):
    cl_att = 'I am an A class attribute'

class  B(A):
    cl_att += ' modified for B type'

class  C(A):
    cl_att += ' modified for C type'


instA = A()
print insAt.cl_att
>>> I am an A class attribute

instB = B()
print instB.cl_att
>>> I am an A class attribute modified for B type

instC = C()
print instC.cl_att
>>> I am an A class attribute modified for C type

print instA.cl_att
>>> I am an A class attribute

简而言之,我希望能够“使用然后覆盖”父类的类属性。

【问题讨论】:

    标签: python class subclassing


    【解决方案1】:

    引用父类属性并连接到它:

    class  A(object):
        cl_att = 'I am an A class attribute'
    
    class  B(A):
        cl_att = A.cl_att + ' modified for B type'
    
    class  C(A):
        cl_att = A.cl_att + ' modified for C type'
    

    类体的执行很像函数,本地名称构成类属性。 cl_att 不存在于为BC 创建主体的新“函数”中,因此您需要直接引用基类上的属性。

    演示:

    >>> class  A(object):
    ...     cl_att = 'I am an A class attribute'
    ... 
    >>> class  B(A):
    ...     cl_att = A.cl_att + ' modified for B type'
    ... 
    >>> class  C(A):
    ...     cl_att = A.cl_att + ' modified for C type'
    ... 
    >>> A.cl_att
    'I am an A class attribute'
    >>> B.cl_att
    'I am an A class attribute modified for B type'
    >>> C.cl_att
    'I am an A class attribute modified for C type'
    

    【讨论】:

      【解决方案2】:

      假设您只有一个父类,您可以在子类的答案末尾使用定义的inherit_and_append 装饰器来获得所需的结果,如下所示:

      class  A(object):
          cl_att = 'I am an A class attribute'
      
      @inherit_and_append('cl_att')
      class  B(A):
          cl_att = ' modified for B type'
      
      @inherit_and_append('cl_att')
      class  C(A):
          cl_att = ' modified for C type'
      

      如果有更高级的需求或条件,可以进一步扩展装饰器。

      class inherit_and_append(object):
          def __init__(self, *attrs):
              super(inherit_and_append, self).__init__()
      
              self._attrs = attrs
      
          def __call__(self, klass):
              parent = klass.__bases__[0]  # Assuming you have a single parent class
              for attr in self._attrs:
                  if not hasattr(parent, attr):
                      raise AttributeError("'{}' class has no '{}' attribute".format(parent.__name__, attr))
      
                  parent_value = getattr(parent, attr)
                  klass_value = getattr(klass, attr)
                  setattr(klass, attr, parent_value + klass_value)
      
              return klass
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-02
        • 2017-09-29
        • 2018-02-27
        • 2023-03-20
        相关资源
        最近更新 更多