0

I was wondering how to achieve this behavior.

When you call a variable in python, it directly displays some value.

like:

>> a= 5
>> a
5

libraries like numpy also do this

>> a = np.array([1,2])
>> a
>> array([1,2])

Happens something like that right? So i want to emulate that behaviour to build a class

class example(object):
   def __init__(self,intputs):
       self.out = inputs
...
instance = example(inputs)

such that when i write

instance

it were directly equivalent to do

instance.out

Cos the most similar thing I know is setting call to do that but in that case it would be calling instance() with those brackets

Juan Felipe
  • 155
  • 1
  • 5

1 Answers1

0

I'm not exactly sure why you want to do this. The proper way to handle printing out the value of a class instance is to provide either a __str__ or __repr__ method for your class (depending on what exactly you want to see), call that method, and print the result. For most cases, a simple __str__ call will suffice:

class example(object):
    def __init__(self,intputs):
        # your init code here

    def __str__(self):
        # construct a string for the class value and return it
        return str(self.some_value)

You would then do something like the following to get the string representation in your code:

instance = example(some_value)
print(str(instance))

Here's a helpful article and relevant SO question on the difference between __str__ and __repr__.

Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74