2013-03-05 89 views
1

在下面的代碼中,有人可以告訴我,在標記爲#whereami(第3行)的行中,我如何能夠確定我現在在類Person中而不是在實例化的Programmer中目的。標識正在運行代碼的類

理想情況下,我想要一個類/類型的對象,但類名稱'人'會做,如果不能返回。

class Person(object): 
    def opinion(self): 
     #whereami 
     print "Time for a cup of tea" 

class Programmer(Person): 
    def opinion(self): 
     super(Programmer, self).opinion() 
     print "There is no spoon" 

if '__name__' == '__main__': 
    programmer = Programmer() 
    programmer.opinion() 

回答

0

使用

type('object') 

見下使用Python3.2

class Person(object): 
    def opinion(self): 
     print(type(self)) 
     print ("Time for a cup of tea") 

class Programmer(Person): 
    def opinion(self): 
     super(Programmer, self).opinion() 
     print ("There is no spoon") 

if '__name__' == '__main__': 
    programmer = Programmer() 
    programmer.opinion() 

p = Person() 
p.opinion() 
print('\n') 
pg = Programmer() 
pg.opinion() 

結果

<class '__main__.Person'> 
Time for a cup of tea 


<class '__main__.Programmer'> 
Time for a cup of tea 
There is no spoon 

你可以告訴大家,第一個結果是調用示例由「人」類編輯。

+0

謝謝。沒有其他方式可以訪問相同的信息? – 2013-03-05 12:43:52

1

嘗試插入下面的行

className=self.__class__.__name__ 

通過className變量會對當前的類名的值作爲一個字符串