Wednesday, January 17, 2018

python __repr__ vs __str__ and cast variable, isinstance tuple vs list, dict for repr(), str(), int(), eval(code or string)

class Point3D(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z

def __repr__(self):
return str(self.z)

def __str__(self):
return "(%s, %s, %s)" % (self.x, self.y, self.z)


my_point = Point3D(1, 2, 3)
print(my_point)
v = str(repr(my_point))
b = isinstance(v, str)
if b:
v1 = int(v) + 1
s = str(v1) + ';'
print(s)
else:
print(b, ";")

print(isinstance(('a', 'b'), tuple))
print(isinstance(['a', 'b'], list))

dic = {'abc': 'abc', 'def': {'a1': 'a1v', 'a2': 'a2v'}}
for elem in dic.values():
if isinstance(elem, dict):
for ndx, item in elem.items():
print(ndx, ' => ', item, 'is ')
for i in item:
print(i)

No comments: