Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

Coming from a Java background, I understand that __str__ is something like a Python version of toString (while I do realize that Python is the older language).

So, I have defined a little class along with an __str__ method as follows:

class Node:

    def __init__(self, id):

        self.id = id 

        self.neighbours = []

         self.distance = 0

    def __str__(self):

       return str(self.id)

I then create a few instances of it:

uno = Node(1)

due = Node(2)

tri = Node(3)

qua = Node(4)

Now, the expected behaviour when trying to print one of these objects is that it's associated value gets printed. This also happens.

print uno

yields

1

But when I do the following:

uno.neighbours.append([[due, 4], [tri, 5]])

and then

print uno.neighbours

I get

[[[<__main__.Node instance at 0x00000000023A6C48>, 4], [<__main__.Node instance at 0x00000000023A6D08>, 5]]]

Where I expected

[[2, 4], [3, 5]]

What am I missing? And what otherwise cringe-worthy stuff am I doing?

1 Answer

0 votes
by (106k points)

You can resolve your doubt by the below-mentioned code:-

class Pet(object):

     def __init__(self, name, species):

             self.name = name

             self.species = species

     def getName(self):

            return self.name

     def getSpecies(self):

            return self.species

     def Norm(self):

            return "%s is a %s" % (self.name, self.species)

if __name__=='__main__':

      a = Pet("Ram", "Man")

      print(a)

The above code returns:-

<__main__.Pet object at 0x029E2F90>

Whereas the code with "str" return something different which is as follows:-

class Pet(object):

    def __init__(self, name, species):

         self.name = name

         self.species = species

    def getName(self):

         return self.name

    def getSpecies(self):

         return self.species

    def __str__(self):

         return "%s is a %s" % (self.name, self.species)

if __name__=='__main__':

    a = Pet("Ram", "Man")

    print(a)

This code will returns:

Ram is a Man

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)

Browse Categories

...