How can I print a Python class?

I have a class that contains several functions (most of them contain code that parses smth., Gets all the information it needs, and prints it out). I am trying to print a class, but I get smth. e.g. <_main_.TestClass instance at 0x0000000003650888> . Sample code:

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

      

When I print functions outside the class - everything is fine. What am I doing wrong and how can I print the class?

Thank!

+3


source to share


2 answers


This is expected behavior. Python cannot know how a class is represented unless you define a method __str__

or __repr__

to give the class a string representation.

To be clear: __repr__

it is usually defined to create a string that can be evaluated back to a similar object (in your case TestClass()

). By default, it __repr__

outputs the <__main__.TestClass instance at 0xdeadbeef>

thing you see.

Example __repr__

:

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

      



__str__

can be defined to get a human-readable "description" of the class. If not specified, you will receive __repr__

.

Example __str__

:

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

      

+5


source


It sounds like you want to print an instance of the class, not the class itself. Define an __str__

or method __repr__

that returns a string to be used when printing an instance.

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



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

+1


source







All Articles