Tejesh Reddy
Tejesh Reddy

Reputation: 51

How to print class member's data in python?

I have

class CanIdPropType:
    def __init__(self):
        self.arbitration_id = None
        self.dlc = 0
        self.data = {}
        self.timestamp = ""

def Receive():
  CanMessage = CanIdPropType()
  print('CanMessage',CanMessage)

In the code above I am trying to print 'CanMessage' but it is printing the address of the class. I want to print the class members values without using bellow format: CanMessage.dlc, CanMessage.data

Upvotes: 0

Views: 248

Answers (3)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

You can override the dunder method __str__ to get the format you need.

You can iterate over the __dict__ which is a dictionary that stores the attributes of the class to get the list of attributes you want

class CanIdPropType:
    def __init__(self):
        self.arbitration_id = None
        self.dlc = 0
        self.data = {}
        self.timestamp = ""

    def __str__(self):

        #Iterate over all attributes, and create the representative string
        return ', '.join([f'{self.__class__.__name__}:{attr}' for attr in self.__dict__])

CanMessage = CanIdPropType()
print(CanMessage)

The output will be

CanIdPropType:arbitration_id, CanIdPropType:dlc, CanIdPropType:data, CanIdPropType:timestamp

Upvotes: 1

ncica
ncica

Reputation: 7206

Use .__dict__:

For normal objects, the __dict__ object creates a separate dict object, which stores the attributes, and __getattribute__ first tries to access it and get the attributes from there (before attempting to look for the attribute in the class by utilizing the descriptor protocol, and before calling __getattr__). The __dict__ descriptor on the class implements the access to this dictionary.

class CanIdPropType:
    def __init__(self):
        self.arbitration_id = None
        self.dlc = 0
        self.data = {}
        self.timestamp = ""

def Receive():
  CanMessage = CanIdPropType()
  print('CanMessage',CanMessage.__dict__)

Receive()

output:

CanMessage {'arbitration_id': None, 'dlc': 0, 'data': {}, 'timestamp': ''}

Upvotes: 0

olinox14
olinox14

Reputation: 6643

You can change the default way of an object is represented by overriding the __repr__ method.

For example:

class CanIdPropType:
    def __init__(self):
        self.arbitration_id = None
        self.dlc = 0
        self.data = {}
        self.timestamp = ""

    def __repr__(self):
        return f"<CanIdPropType: {self.arbitration_id}, {self.dlc}>"

Upvotes: 2

Related Questions