错误:找不到人

时间:2013-05-25 17:07:35

标签: python python-2.7

#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()

2 个答案:

答案 0 :(得分:5)

您的问题可以简化为:

 class Person:
      print(Person)

这会引发NameError。构造类时,将执行类的主体并将其放在特殊的命名空间中。然后将该命名空间传递给typeprint(Person)负责实际创建类。

在您的代码中,您在实际创建类Person之前尝试type(在执行类的主体的阶段 - 在它传递给{之前) {1}}并绑定到类名称),这会导致NameError

答案 1 :(得分:0)

您希望在调用print时让您的类返回某些信息,并且您还希望在创建该类的实例时打印该信息。这样做的方法是为您的班级定义__repr__(或__str__,以获取有关Difference between __str__ and __repr__ in Python)方法的更多信息。然后,每次在类的实例上调用print时,它将打印该__repr__方法返回的内容。然后,您只需在__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.