I just started to code in Python. I am using Windows 8. I have the following code and it is not working. However the code worked fine on Ubuntu. The python version is same on both OS.
class test:
def __init__(self):
def add(self,a,b):
print a+b
class subclass(test):
print "testing"
s = subclass()
s.add(1,2)
The Output is given below:
s.add(1,2)
AttributeError: subclass instance has no attribute 'add'
PS: There are no ident problems.
3 Answers 3
If your code is indented as desired then the add() function only exists within __init__() and never becomes part of the class. There is no possible way that your code could work, even if you had an instance of test instead.
1 Comment
code works seems to mean runs without exceptions raised.If indentation is ok, as stated, you should add
self.add = add
to your __init__. Right now you declare add function in local __init__ scope, but assign it nowhere, so it gets immediately garbage collected.
update
As there is no indent problems stated by author seems to refer to code being successfully executer without IndentationError raised, correct line of action seems to be equally indent __init__ and add, to make them both instance methods, and remove empty __init__ or add pass placeholder:
class test:
def __init__(self): pass
def add(self,a,b):
print a+b
class subclass(test):
print "testing"
Comments
Why you have an empty init method? If you need it, the init implementation cant be blank. You can try:
class test:
def __init__(self):
pass
def add(self, a, b):
print a+b
Or:
class test:
def add(self, a, b):
print a+b
addwithin__init__method?There are no ident problemsmeans no indent errors are reported back :) You should not add, but remove some (5 it seems) spaces before add, and remove unuseddef __init__(self):line__init__method should contain at-least one valid line of code after declaration. If you don't want to add any just write apassstatement. dpaste.com/hold/1510285__init__method to have a body, but you didn't write one. Your fix movedaddinto the body of__init__, which is not a solution.