如何在Python中访问稍后阶段添加的类属性?

时间:2016-10-04 08:34:57

标签: xcode python-2.7

 class Employee:
 'Common base class for all employees'
  empCount = 0

 def __init__(self, name, salary):
   self.name = name
    self.salary = salary
  Employee.empCount += 1

def displayCount(self):
  print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
   print "Name : ", self.name,  ", Salary: ", self.salary

"This would create first object of Employee class"
   emp1 = Employee("Zara", 2000)
 "This would create second object of Employee class"
  emp2 = Employee("Manni", 5000)
  emp1.displayEmployee()
  emp2.displayEmployee()
  print "Total Employee %d" % Employee.empCount

如果我稍后添加age属性为emp1.age = 7。然后我该如何访问它?

我试过打印"员工年龄1:%d" %d self.age 但它给出了错误。

1 个答案:

答案 0 :(得分:0)

你得到的错误是什么? 您创建的外部变量将不在类命名空间中,但它存在于实例命名空间中。 所以你不能用类名来获取它,尝试用object.__dict__打印你会找到变量。