-3
#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()
mgilson
  • 300,191
  • 65
  • 633
  • 696

2 Answers2

5

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
0

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.
Community
  • 1
  • 1
qwwqwwq
  • 6,999
  • 2
  • 26
  • 49