2011-11-22 184 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