python class properties

前端 未结 2 1291
情话喂你
情话喂你 2021-02-14 11:46

I\'m trying to find the best way to extend a class variable. Hopefully an example of the method I\'ve come up with so far will make this clear.

class A(object):         


        
相关标签:
2条回答
  • 2021-02-14 12:10

    Could use a metaclass:

    class AutoExtendingFoo(type):
    
        def __new__(cls, name, bases, attrs):
            foo = []
            for base in bases:
               try:
                   foo.extend(getattr(base, 'foo'))
               except AttributeError:
                   pass
            try:
                foo.extend(attrs.pop('foo_additions'))
            except KeyError:
                pass
            attrs['foo'] = foo
            return type.__new__(cls, name, bases, attrs)
    
    class A(object):
        __metaclass__ = AutoExtendingFoo
        foo_additions = ['thing1', 'thing2']
        # will have A.foo = ['thing1', 'thing2']
    
    class B(A):
        foo_additions = ['thing3', 'thing4']
        # will have B.foo = ['thing1', 'thing2', 'thing3', 'thing4']
    
    class C(A):
        pass
        # will have C.foo = ['thing1', 'thing2']
    
    class D(B):
        pass
        # will have D.foo = ['thing1', 'thing2', 'thing3', 'thing4']
    
    0 讨论(0)
  • 2021-02-14 12:17

    I definitively would go for instance-properties. (if I got it right, they are not bound to be static for your case?!)

    >>> class A:
    ...     @property
    ...     def foo(self):
    ...         return ['thin', 'another thing']
    ...
    >>> class B(A):
    ...     @property
    ...     def foo(self):
    ...         return super().foo + ['stuff', 'thing 3']
    ...
    >>> B().foo
    ['thin', 'another thing', 'stuff', 'thing 3']
    
    0 讨论(0)
提交回复
热议问题