#C:/Python32
class Person:
def __init__(self, name = "joe" , age= 20 , salary=0):
self.name = name
self.age = age
self.salary = salary
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
print(Person)
class Employee(Person):
def __init__(self, name, age , salary ):
Person. __init__ (self,name = "Mohamed" , age = 20 , salary = 100000)
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
print(Employee)
p= Person()
e = Employee()

- 300,191
- 65
- 633
- 696

- 1
- 1
-
Why do you have a Python32 shebang and a python-2.7 tag? – Wooble Jun 07 '13 at 14:31
2 Answers
Your problem can be simplified to:
class Person:
print(Person)
This will raise a NameError
. When constructing a class, the body of the class is executed and placed in a special namespace. That namespace is then passed to type
which is responsible for actually creating the class.
In your code, you're trying to print(Person)
before the class Person
has actually been created (at the stage where the body of the class is being executed -- Before it gets passed to type
and bound to the class name) which leads to the NameError
.

- 300,191
- 65
- 633
- 696
-
mgilson is right, to go further you can replace your print with a print(locals()), it will show you what is defined when executing the class body. – deufeufeu May 25 '13 at 17:16
-
@deufeufeu -- You'd also need to `print(globals())` as well I believe. – mgilson May 25 '13 at 17:18
-
Yes, I assumed that in this case we could exclude globals() from giving info about the class itself. – deufeufeu May 25 '13 at 17:21
-
It appears that you want to have your class return certain information when print is called on it, and that you also want that information printed when you create an instance of that class. The way you would do this is to define a __repr__
( or __str__
, for more on that see Difference between __str__ and __repr__ in Python ) method for your class. Then everytime print is called on an instance of your class, it will print what is returned by that __repr__
method. Then you can just add a line to your __init__
method, that prints the instance. Within the class, the current instance is referred to by the special self
keyword, the name of the class is only defined outside the scope of the class, in the main namespace. So you should call print(self)
and not print(Person)
. Here's some code for your example:
class Person:
def __init__(self, name = "joe" , age= 20 , salary=0):
self.name = name
self.age = age
self.salary = salary
print(self)
def __repr__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
joe = Person()
>>> My name is joe, my age is 20 , and my salary is 0.