2016-10-04 41 views
-2
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 

如果我以後添加年齡屬性爲emp1.age = 7。那我該如何訪問它?如何訪問在後期添加的Python中的類屬性?

我試過 - 打印出「employee1的年齡:%d」%d self.age 但是它給的錯誤。

+0

它應該工作,但檢查你的問題:縮進是可怕的,「其給予錯誤」對我們不是很有用。 –

回答

0

你得到的錯誤是什麼? 您創建的外部變量不會在類名稱空間中,而是存在於實例名稱空間中。 所以你不能用類名來獲取它,嘗試打印object.__dict__你會發現變量。

相關問題