SantoshGupta7
SantoshGupta7

Reputation: 6197

How to directly get an object's description; the output of print(object)

If you do

print(object)

You get an description of that object.

How can I directly access this description?

I tried type(object), and object.class but they didn't get the same exact description.

Upvotes: 0

Views: 50

Answers (2)

MisterMonk
MisterMonk

Reputation: 359

Use the Dunder Methods of the objects.

  • obj.__repr__()
  • obj.__str__()

or

  • repr(obj)
  • str(obj)

It depends on the object how and if this methods are implemented

import numpy as np

arr = np.ndarray()

print(arr.__repr__())
# prints: array([[1]])

print(arr.__str__())
# prints: [[0]]

Upvotes: 1

jamesfranco
jamesfranco

Reputation: 520

object.__ str__() 

is what you want. Alternatively

object.__repr__() 

sometimes differs from

__str__ 

with more detail, but is generally more difficult to read.

Edit:

Needed to add () for method to give the description

Upvotes: 1

Related Questions