2013-05-25 112 views
-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() 
+0

为什么你有Python32 shebang和python-2.7标签? – geoffspear

回答

5

你的问题可以简化为:

class Person: 
     print(Person) 

这将引发NameError。构建类时,类的主体将被执行并放置在特殊的命名空间中。该名称空间然后传递给type,它负责实际创建类。

在你的代码,你想print(Person)Person实际上已创建的类(在其中正在执行类的主体阶段 - 它被传递给type之前并绑定到类名)之前这导致了NameError

+0

mgilson是正确的,为了进一步您可以用打印(locals())来替换您的打印,它会告诉您什么是在执行类体时定义的。 – deufeufeu

+0

@deufeufeu - 你也需要'print(globals())'我相信。 – mgilson

+0

是的,我认为在这种情况下,我们可以排除globals()给出关于类本身的信息。 – deufeufeu

0

看起来您希望在您的类上调用print时返回某些信息,并且您还希望在创建该类的实例时打印该信息。你要这样做的方式是为你的班级定义一个__repr__(或__str__,详情请参阅Difference between __str__ and __repr__ in Python)。然后,每次打印都会在您班级的一个实例上调用,它将打印该方法返回的内容。然后你可以添加一行到你的__init__方法,打印实例。在该类中,当前实例由特殊的self关键字引用,该类的名称仅在该类的范围之外定义在主名称空间中。所以你应该拨打print(self)而不是print(Person)。这里是你的例子的一些代码:

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.