Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #42578 > unrolled thread

Re: extending class static members and inheritance

Started byArnaud Delobelle <arnodel@gmail.com>
First post2013-04-02 16:24 +0100
Last post2013-04-02 16:24 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: extending class static members and inheritance Arnaud Delobelle <arnodel@gmail.com> - 2013-04-02 16:24 +0100

#42578 — Re: extending class static members and inheritance

FromArnaud Delobelle <arnodel@gmail.com>
Date2013-04-02 16:24 +0100
SubjectRe: extending class static members and inheritance
Message-ID<mailman.8.1364916291.3114.python-list@python.org>
On 2 April 2013 14:27, Fabian PyDEV <pydev@hotmail.com> wrote:
> Hi All,
>
> I have a question.
>
> Let says I have the following two classes:
>
> class Base(object):
>         __mylist__ = ["value1", "value2"]
>
>         def somemethod(self):
>                 pass
>
>
> class Derived(Base):
>         __mylist__ = ["value3", "value4"]
>
>         def anothermethod(self):
>                 pass
>
>
>
>
> what I would like to accomplish is that the class Derived has the member __mylist__ extended or merged as ["value1", "value2", "value3", "value4"].
>
> Is there anyway I could accomplish this?
>
> I was thinking on accomplishing this as follows:
>
>
> class Derived(Base):
>         __mylist__ = Base.__mylist__ + ["value3", "value4"]
>
>         def anothermethod(self):
>                 pass
>
>
> Is there a better way? Perhaps a decorator?

class Base(object):

	mybits = ["value1", "value2"]

	@classmethod
	def mylist(cls):
		return sum((getattr(p, 'mybits', []) for p in cls.mro()[::-1]), [])


class Derived(Base):

	mybits = ["value3", "value4"]


class FurtherDerived(Derived):

	mybits = ["value5"]


>>> Derived.mylist()
['value1', 'value2', 'value3', 'value4']
>>> FurtherDerived.mylist()
['value1', 'value2', 'value3', 'value4', 'value5']

HTH

-- 
Arnaud

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web