Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print a Python class? [duplicate]

Tags:

python

class

I have a class that contains several functions(most of it contains code that parses smth., get all necessary info and print it). I'm trying to print a class but i get smth. like <_main_.TestClass instance at 0x0000000003650888>. Code sample:

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 out of class - all is ok. What i'm doing wrong and how can I print a class?

Thanks!

like image 638
Alex A Avatar asked Feb 19 '13 07:02

Alex A


People also ask

How do you duplicate a class object in Python?

Copy an Object in Python In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.

Can you copy an instance of a class in Python?

Yes, you can use copy. deepcopy . so just c2 = copy.

What is __ repr __ in Python?

Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.

What is __ str __ in Python?

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.


1 Answers

That's the expected behaviour. Python can't know how the class is represented unless you define a __str__ or __repr__ method to give the class a string representation.

To be clear: __repr__ is usually defined to produce a string that can be evaluated back into a similar object (in your case, TestClass()). The default __repr__ prints out 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 produce a human-readable "description" of the class. If not supplied, you get __repr__.

Example __str__:

def __str__(self):
    return "(TestClass instance)"
like image 114
nneonneo Avatar answered Sep 27 '22 22:09

nneonneo