Nick Sahno
Nick Sahno

Reputation: 53

Getting access to class's variables inside another class's def

I'm trying override a str method in Person() class:

'''class Person(object):

def __init__(self, Nose = None, Neck = None, RShoulder = None, RElbow = None, RWrist = None, LShoulder = None, LElbow = None, LWrist = None, MidHip = None, RHip = None, RKnee = None, RAnkle = None, LHip = None, LKnee = None, LAnkle = None, REye = None, LEye = None, REar = None, LEar = None, LBigToe = None, LSmallToe = None, LHeel = None, RBigToe = None, RSmallToe = None, RHeel = None):
    self.Nose = Nose
    self.Neck = Neck
    self.RShoulder = RShoulder
    self.RElbow = RElbow
    self.RWrist = RWrist
    self.LShoulder = LShoulder
    self.LElbow = LElbow
    self.LWrist = LWrist
    self.MidHip = MidHip
    self.RHip = RHip
    self.RKnee = RKnee
    self.RAnkle = RAnkle
    self.LHip = LHip
    self.LKnee = LKnee
    self.LAnkle = LAnkle
    self.REye = REye
    self.LEye = LEye
    self.REar = REar
    self.LEar = LEar
    self.LBigToe = LBigToe
    self.LSmallToe = LSmallToe
    self.LHeel = LHeel
    self.RBigToe = RBigToe
    self.RSmallToe = RSmallToe
    self.RHeel = RHeel
def __str__(self):
    return 'Nose = %s\nNeck = \n%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s'%(self.Nose,self.Neck,self.RShoulder,self.RElbow,self.RWrist,self.LShoulder,self.LElbow,self.LWrist,self.MidHip,self.RHip,self.RKnee,self.RAnkle,self.LHip,self.LKnee,self.LAnkle,self.REye,self.LEye,self.REar,self.LEar,self.LBigToe,self.LSmallToe,self.LHeel,self.RBigToe,self.RSmallToe,self.RHeel)'''

And I want to find more elegant way to return a string which will look like that:

Nose = something

Neck = something
...
...
...

Upvotes: 0

Views: 38

Answers (1)

stovfl
stovfl

Reputation: 15533

Question: elegant way to return a string which will look like ...

You can use the built-in vars function to get the __dict__ of the class variable and format it using .format(... and .join(....


Reference:


class Person:
    def __init__(self, **kwargs):
        self.Nose = kwargs.get('Nose', None)
        self.Neck = kwargs.get('Neck', None)
        self.RShoulder = kwargs.get('RShoulder', None)

    def __str__(self):
        return '\n'.join(('{} = {}'
                          .format(k, v) for k, v in vars(self).items()))


p = Person(Nose=1, Neck=1)    
print(p)

Output:

Nose = 1
Neck = 1
RShoulder = None

Tested with Python: 3.6

Upvotes: 1

Related Questions