0

Code:

class abc():
    def __init__(self,x):
        pass

a = abc(2)
print(a)

Desired OP:

2

Current OP:

<__main__.abc object at 0x000002736F8D7128>

How to get some data when an object is called instead of the default message about the object location

The same way when:

import numpy as np
a = np.array([1,2,3])
print(a)

Gives OP

[1 2 3]

1 Answers1

0

You are trying to print the object's string representation using print statement that's why you are getting <__main__.abc object at 0x000002736F8D7128> If you want to modify that representation you either have to override the __str__ or __repr__ method.

For Example,

class abc():
    def __init__(self,x):
        self.X = x

    def __str__(self):
        return str(self.X)

OR,

class abc():
    def __init__(self,x):
        self.X = x

    def __repr__(self):
        return str(self.X)

Now, when you call print(abc(2)) output will be 2.

Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53