3

I want to set the name of a class to one of the variables within the class so that when I print classes I get their names, I've tried setting __name__ but it did not work.

this is my class

class SNMPData(object):
    def __init__(self, device='', speed_down=0, speed_up=0, bgp_peer_state='', bgp_summary='', error=''):
        self.device = device
        self.speed_down = speed_down
        self.speed_up = speed_up
        self.bgp_peer_state = bgp_peer_state
        self.bgp_summary = bgp_summary
        self.error = error
        self.__name__ = device

I create a list of objects then try print them

>>> list = [SNMPData(device='dev_1',speed_down=1),SNMPData(device='dev_2',speed_down=2)]
>>> print(list)
[<SNMPData object at 0x7ff052a42ef0>, <SNMPData object at 0x7ff052a42b38>]
>>>

instead of SNMPData object at 0x.... is it possible to print

['SNMPData dev_1','SNMPData dev_2']

instead?

codeforester
  • 39,467
  • 16
  • 112
  • 140
AlexW
  • 2,843
  • 12
  • 74
  • 156
  • 2
    You are looking for [`__repr__`](https://stackoverflow.com/questions/1984162/purpose-of-pythons-repr) – Wondercricket Sep 05 '17 at 15:20
  • If the description is "small enough", it's recommended to restate how to create the object again, e.g. `SNMPData(device='{device}')`, but if it's going to be very state heavy, just do something generic ``. – Nick T Sep 05 '17 at 15:26

5 Answers5

5

You are looking to define __repr__ which should return a printable representation of the object. The official definition of __repr__

repr(object):

Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a repr() method.

bottom line is that the output from __str__ is meant to be readable by human ** whereas the output from **__repr__ is meant to be read by the Python interpreter. so when you give the string to the interpreter, it should recreate the object. Also If an object doesn't have a __str__ method then __repr__ is used instead.

OLIVER.KOO
  • 5,654
  • 3
  • 30
  • 62
3

Each class has a __repr__ and __str__ function which takes a single argument, self, representing the object itself. The __repr__ function returns the true string representation of the object and the __str__ function is used for str(obj) which is used for printing.

class SNMPData(object):
    def __init__(self, device='', speed_down=0, speed_up=0, bgp_peer_state='', bgp_summary='', error=''):
        ...
    def __repr__(self):
        return '{} {}'.format(self.__class__.__name__, self.device)

You can do the same for __str__(self) if you want to observe this behaviour for printing.

Nick T
  • 25,754
  • 12
  • 83
  • 121
hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50
  • 1
    Note that you don't need to hardcode `SNMPData`: you can use `self.__class__.__name__`. – erip Sep 05 '17 at 15:25
2

You are able to change a text representation of your custom object by overriding __repr__ and __str__ methods:

...
def __repr__(self):
    return self.__class__.__name__ + ' ' + self.device
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

Define __repr__(self) and __str__(self).

The former is the "official" string representation. The latter is what is returned when you cast the object to a str.

erip
  • 16,374
  • 11
  • 66
  • 121
1

Generalizing some of the other answers, you could do:

def __str__(self):
    return '{self.__class__.__name__} {self.device}'.format(self=self)
Arda Arslan
  • 1,331
  • 13
  • 24