I’m running windows 7, using python 2.7.3, and I am getting an inheritance error that I can’t figure out why. I’ve done a good bit of searching but haven’t found too much related as of yet.
My problem is that I keep getting a AttributeError when I try to inherit from one class to another. The basic structure I have goes something like this:
# pymyClass.py
class myClass(object):
def __init__(self,aList=None):
if aList is not None:
myList = aList
else:
myList = ['','','','','']
def reset(self,aList=None):
if aList is not None:
myList = aList
else:
myList = ['','','','','']
#other methods operate without issue
# pymySecondClass.py
import pymyClass
class mySecondClass(pymyClass.myClass):
def __init__(self,aList=None):
pymyClass.myClass(aList)
# pymyThirdClass.py
import pymySecondClass
class myThirdClass(pymySecondClass.mySecondClass):
def __init__(self,aList=None):
pymySecondClass.mySecondClass(aList)
def useList(self,aList=None):
self.reset(aList)
print self.myList
#pymyObj.py
import pymyThirdClass
myObj = pymyThirdClass.myThirdClass(['a','b','c','1','2'])
myObj.useList()
…but it errors out when I call instantiate the myThirdClass() and call useList(), saying,
AttributeError: 'myThirdClass' object has no attribute 'myList'
I actually compiled my example here, and got the same issue, so I’m thinking inheritance doesn’t work the way I’m expecting. I’ve checked the python documentation, but maybe not close enough? If anyone could help me out here that would be very much appreciated.
I’m thinking I may have to just manually include the field “myList” in the myThirdClass constructor, but that seems incredibly lame. Thanks in advance!
You never actually attach
myListto the instance anywhere. To do that (inside a method), you need to do:rather than just:
where
selfis the conventional name for the first argument passed to a method.You’ve also got some problems with what calling the base classes on your derived classes.
Some people don’t like to do it as
Foo.__init__(self)— Those people usesuper(which is Ok too as long as you know what you’re doing).