2011-11-22 140 views
1

我有这个在一个类中设置A或B的python代码。我想打印什么这个类接收:在python中打印一个变量

if options.A: 
    print "setting A" 
    class TmpClass(A): pass 
else: 
    print "nothing set in the command line => setting to B" 
    class TmpClass(B): pass 

print "selected=",TmpClass 

我想看看A或B的输出,但我看到:

selected= TmpClass 
+1

这看起来很奇怪。你确定你知道你在做什么吗?如果不是,请再次研究OOP,因为显然你不了解这个概念。 –

+0

你有两个班'A'和'B'?因为你正在做的是创建一个从'A'或'B'继承的新类'TmpClass'。 –

+0

对不起....这个问题并不代表我的问题。我会尽快编辑它。 – mahmood

回答

3

你的代码是干什么的,翻译成英文是:

if option.A has a value that evaluates to True: 
    define an empty class called "TmpClass" that inherits from the object called "A" 
otherwise: 
    define an empty class called "TmpClass" that inherits from the object called "B" 

现在,如果什么代码实际上做的确实是您的本意,我猜测是,你想要什么可以知道是否你的班级是以A或B为基础的......如果我是对的,那么你想要在最后有一行:

print('TmpClass inherits from : %s' % TmpClass.__bases__) 

HTH!

+0

辉煌......那正是我的意思:) – mahmood

0

A和B是传递给类在这里正式参数, A和B

的不是实际值
1

您可以分配类变量,而无需创建它们的实例:

if options.A: 
    print "setting A" 
    TmpClass = A 
else: 
    print "nothing set in the command line => setting to B" 
    TmpClass = B 

print "selected=",TmpClass 
1

你可以看看使用isinstance()。例如:

class MyBaseClass(): 
    def __init__(self): 
     self.cType = 'Base' 

    def whichClass(self): 
     print 'Class type = {0}'.format(self.cType) 

     if isinstance(self,DerivedClassA): 
      print 'Derived Class A' 
     elif isinstance(self,DerivedClassB): 
      print 'Derived Class B' 
     elif isinstance(self,MyBaseClass): 
      print 'Not A or B' 
     else: 
      print 'Unknown Class' 

class DerivedClassA(MyBaseClass): 
    def __init__(self): 
     self.cType = 'Class A' 

class DerivedClassB(MyBaseClass): 
    def __init__(self): 
     self.cType = 'Class B' 


Then Run: 

base = MyBaseClass() 
a = DerivedClassA() 
b = DerivedClassB() 
a.whichClass() 
>> Class type = Class A 
>> Derived Class A 
b.whichClass() 
>> Class type = Class B 
>> Derived Class B 
base.whichClass() 
>> Class type = Base 
>> Not A or B