如何打印Python类?

时间:2013-02-19 07:25:28

标签: python class

我有一个包含多个函数的类(其中大部分包含解析smth的代码,获取所有必要的信息并打印出来)。我正在尝试打印一个班级,但我得到了smth。例如< _ main _。TestClass实例位于0x0000000003650888> 。代码示例:

from lxml import html
import urllib2
url = 'someurl.com'


class TestClass:

    def testFun(self):
        f = urllib2.urlopen(url).read()
        #some code

        print 'Value for ' +url+ ':', SomeVariable

    def testFun2(self):
        f2 = urllib2.urlopen(url).read()
        #some code

        print 'Value2 for ' +url+ ':', SomeVariable2

test = TestClass()
print test

当我在课外打印功能时 - 一切正常。我做错了什么,如何打印课程?

谢谢!

2 个答案:

答案 0 :(得分:6)

这是预期的行为。除非您定义__str____repr__方法为类提供字符串表示形式,否则Python无法知道如何表示类。

要明确:__repr__通常被定义为生成一个字符串,可以将其评估回​​类似对象(在您的情况下为TestClass())。默认__repr__会打印出您看到的<__main__.TestClass instance at 0xdeadbeef>内容。

示例__repr__

def __repr__(self):
    return self.__class__.__name__ + '()' # put constructor arguments in the ()
可以定义

__str__以生成类的人类可读的“描述”。如果未提供,则会获得__repr__

示例__str__

def __str__(self):
    return "(TestClass instance)"

答案 1 :(得分:1)

看起来你想要打印类的实例而不是类本身。定义一个__str____repr__方法,该方法返回打印实例时要使用的字符串。

请参阅:http://docs.python.org/2/reference/datamodel.html#object.__repr__

http://docs.python.org/2/reference/datamodel.html#object.__str__