Movatterモバイル変換


[0]ホーム

URL:


calling superclass' method with list positional arg

Roeland Rengelinkr.b.rigilink at chello.nl
Fri Apr 13 06:30:41 EDT 2001


Steven Haryanto wrote:>> My Bag's constructor accepts a list positional args to fill> the object with initial data, so I can conveniently create> a bag initially filled with stuff like this:>> mybag = Bag("apples", "oranges", "money")>> BagOTricks is a subclass of Bag, and it needs to do something> else but let the superclass do the actual data filling.> Currently I do it like this:>> class Bag:>>      def __init__(self, *items):>          self._items = list(items)>>      def add(self, item):>          self._items.append(item)>> class BagOTricks(Bag):>>      def __init__(*args):>          self = args_[0]>          # do something else first...>>          # then pass the items to superclass' constructor>          apply(Bag.__init__, args_)>> Is there an elegant way to do this so I can still declare> Bag's __init__ as 'def __init__(self, *items)', but I don't> need to create a temporary list like below?>> class BagOTricks(Bag):>>      def __init__(self, *items):>          # do something else first...>>          # then pass the items to superclass' constructor>          args = list(items)>          args.insert(0, self)Shouldn't that args be a tuple: i.e: args = (self,)+items ?>          apply(Bag.__init__, args)>> Thanks,> SteveI may misunderstand the question, but maybe this is what you mean(Python 2.0+)class BagOTricks(Bag):    def __init__(self, *items):       # do something else       Bag.__init__(self, *items)If you're using 1.5.* and want to avoid the copies, the __init__(*args)methodseems like the best approach On the other hand. why worry about thecopies, the__init__ is not going to take that many arguments is it?Or just not call Bag.__init__. but do the assignment in BagOTricksitself.Hope this helps,Roeland


More information about the Python-listmailing list

[8]ページ先頭

©2009-2025 Movatter.jp