Jump to content

how to define how to print an object

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
denarced

denarced

    Programmer

  • Members
  • PipPipPipPip
  • 182 posts
Is there a way to define how to print a class object like in C++ ?
So if I have a code like this
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
theonejb

theonejb

    Learning Programmer

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

#3
denarced

denarced

    Programmer

  • Members
  • PipPipPipPip
  • 182 posts
Thanks, that did the trick.
Here's an example in case someone else is pondering the problem:
class oldPerson:
    def __init__(self,age):
        self.age = age
    def __str__(self):
        return str(self.age)

paps = oldPerson(102)
print(paps)