在python中打印变量

时间:2011-11-22 09:14:06

标签: python class printing

我有这个在类中设置A或B的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

4 个答案:

答案 0 :(得分: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!

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

A和B是在这里传递给类的正式参数,而不是A和B的实际值。