0

I have a superclass that has a lot of arguments. I want to create a subclass that shares all of those arguments and adds additional one or two arguments. To ommit double-coding, I used a method specified in Avoid specifying all arguments in a subclass :

class Container(Item):

  def __init__(self,**kwargs):
    try: self.is_locked=kwargs.pop('is_locked')
    except KeyError: pass
    super(Container, self).__init__(**kwargs)

  def open(self):
    print "aw ys"

However, when I then try to call an object of a Container class:

> some_container.open()
AttributeError: 'Item' object has no attribute 'open'

It appears as if the some_container is not a Container() but rather an Item() with a single variable is_locked added. What am I doing wrong?

edit: My Item definition:

class Item(object:
def __init__(self,istemplate,id,short,long,type,flags,value,damagerange,damagereductionrange,weight): 
    if istemplate==False:
        self.__class__.instances.append(self)
    self.istemplate=istemplate
(... many variables like that...)
    self.id=id
    self.randomizestuff() 
    if istemplate==True:
        self.__class__.templates.append(copy.deepcopy(self))
Community
  • 1
  • 1
  • What is your `Item` class definition? – Tuan Anh Hoang-Vu Jun 05 '15 at 22:17
  • Oops, sorry. Edited it into main post. – user2551153 Jun 05 '15 at 22:25
  • I assume `some_container` is created like `some_container = Container(...)` – Pynchia Jun 05 '15 at 22:38
  • 1
    I can't replicate your error, though I do have to fiddle with Item to get it to stop throwing errors right off. Make sure you're actually instantiating Container and not Item, as is indicated by the error. – paidhima Jun 05 '15 at 22:38
  • and just due to my curiosity/ignorance: why are you going through `self.__class__` ? Why not simply reach `templates` and `instances` through `self.templates` and `self.instances` ? If they are class attributes, they can be reached through `self.` – Pynchia Jun 05 '15 at 22:43

1 Answers1

0

Okay, after some research it turned out I was in fact referencing not a container in some_container.open() but rather a dynamic item created by a function that creates instances of items from the same template. That function would define new instances as Item(...) rather than Container(...) since it was created before introduction of any subclasses.

some_container=Container(...)
some_container.open()

The above would work from the beginning, hence paidhima couldn't replicate my error.