2013-03-05 45 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变量会对当前的类名的值作为一个字符串