Closed Thread
Results 1 to 3 of 3

Thread: how to define how to print an object

  1. #1
    denarced is offline Programmer
    Join Date
    Jul 2008
    Location
    Joensuu, Finland
    Posts
    182
    Rep Power
    0

    Question how to define how to print an object

    Is there a way to define how to print a class object like in C++ ?
    So if I have a code like this
    Code:
    class node:
        def __init__(self,value=0,left=None,right=None):
            self.value = value
            self.left = left
            self.right = right
    
    n1 = node(4)
    print(n1)
    it would print the 'value'

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Location
    Advertising world
    Posts
    Many

     
  3. #2
    theonejb's Avatar
    theonejb is offline Learning Programmer
    Join Date
    Jul 2009
    Location
    Lahore, Pakistan
    Posts
    52
    Rep Power
    0

    Re: how to define how to print an object

    overload the str method. It's called whenever a string representation of the object is needed, like in a print statement.

  4. #3
    denarced is offline Programmer
    Join Date
    Jul 2008
    Location
    Joensuu, Finland
    Posts
    182
    Rep Power
    0

    Re: how to define how to print an object

    Thanks, that did the trick.
    Here's an example in case someone else is pondering the problem:
    Code:
    class oldPerson:
        def __init__(self,age):
            self.age = age
        def __str__(self):
            return str(self.age)
    
    paps = oldPerson(102)
    print(paps)

Closed Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. learning to use #define
    By jackson6612 in forum C and C++
    Replies: 4
    Last Post: 09-21-2011, 12:36 PM
  2. Replies: 5
    Last Post: 08-15-2011, 05:32 AM
  3. Define Love Error!
    By Guest in forum The Lounge
    Replies: 12
    Last Post: 05-04-2010, 02:40 PM
  4. Define PHP the Long Way
    By Xav in forum PHP Tutorials
    Replies: 8
    Last Post: 06-23-2008, 12:17 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts