Reputation: 1702
I'm learning python out of "core python programming 2nd edition"
Im stuck at the part "How to Create Class instances". Page 84.
The example is as follows:
classes.py:
class FooClass(object):
"""my very first class: FooClass"""
version = 0.1 # class (data) attribute
def __init__(self, nm='John Doe'):
"""constructor"""
self.name = nm # class instance (data) attribute
print'Created a class instance for', nm
def showname(self):
"""display instance attribute and class name"""
print 'Your name is', self.name
print 'My name is', self.__class__.__name__
def showver(self):
"""display class(static) attribute"""
print self.version # references FooClass.version
def addMe2Me(self, x): # does not use 'self'
"""apply + operation to argument"""
return x + x
Then i have to create Class Instances:
in my interpreter i do the follow:
Import classes *
fool = FooClass()
But nothing happends. It should print the init.
also when i use
fool.showname()
and fool.showver
it doesn't print any. It says
FooClass' object has no attribute 'showver
i really want to know what going on here, before i proceed. Hopefully someone can help me out!
Thanks in advance! :)
Upvotes: 3
Views: 4007
Reputation: 27
Well, i am also learning python and i am also referring this book but my book is 1st edition. But, what i analyzed from your code is that it is not indented properly.Please check properly and hope so it will work fine.Thanks.
Upvotes: 3
Reputation: 43899
It looks like you haven't indented the methods of your class. With the following code:
class FooClass(object):
...
def __init__(self, nm='John Doe'):
...
You are declaring a class called FooClass
and a function called __init__
. The class will have a default empty constructor. If you instead indent it as:
class FooClass(object):
...
def __init__(self, nm='John Doe'):
...
You have a class FooClass
with the __init__
method as a constructor.
Upvotes: 4
Reputation: 35059
You appear to have indentation problems. Much like the code in functions, conditionals and loops has to be indented for Python to treat it as "inside" them, your various class methods need to be indented past the class ...:
line to be part of the class rather than merely (separate) functions that happen to be defined after it. So,
class FooClass(object):
"""my very first class: FooClass"""
version = 0.1 # class (data) attribute
def __init__(self, nm='John Doe'):
"""constructor"""
self.name = nm # class instance (data) attribute
print'Created a class instance for', nm
and so on for the rest of your methods.
Upvotes: 2