M
Mangabasi
Howdy,
I would like to create a Point class that lets me use Point instances
like the following example.
other than the x, y, z attributes, these instances should behave like
regular Python lists. I have created something like :
class Point:
def __init__(self, x, y, z = 1):
self.list = [x, y, z]
def __repr__(self):
return str(self.list)
def __str__(self):
return str(self.list)
def __getattr__(self, name):
if name == 'x':
return self.list[0]
elif name == 'y':
return self.list[1]
elif name == 'z':
return self.list[2]
else:
return self.__dict__[name]
def __setattr__(self, name, value):
if name == 'x':
self.list[0] = value
elif name == 'y':
self.list[1] = value
elif name == 'z':
self.list[2] = value
else:
self.__dict__[name] = value
def __getitem__(self, key):
return self.list[key]
def __setitem__(self, key, value):
self.list[key] = value
def __getslice__(self, i, j):
return self.list[i : j]
def __setslice__(self, i, j, s):
self.list[i : j] = s
def __contains__(self, obj):
if obj in self.list:
return True
else:
return False
There must be a way to inherit from the list type without having to
redefine all the methods and attributes that regular lists have.
i.e.
class Point(list):
...
Can someone provide an example?
Thanx in advance
I would like to create a Point class that lets me use Point instances
like the following example.
p = Point(3, 4)
p.x 3
p.y 4
p.z 1
p[0] 3
p[1] 4
p[1] = 5
p.y 5
other than the x, y, z attributes, these instances should behave like
regular Python lists. I have created something like :
class Point:
def __init__(self, x, y, z = 1):
self.list = [x, y, z]
def __repr__(self):
return str(self.list)
def __str__(self):
return str(self.list)
def __getattr__(self, name):
if name == 'x':
return self.list[0]
elif name == 'y':
return self.list[1]
elif name == 'z':
return self.list[2]
else:
return self.__dict__[name]
def __setattr__(self, name, value):
if name == 'x':
self.list[0] = value
elif name == 'y':
self.list[1] = value
elif name == 'z':
self.list[2] = value
else:
self.__dict__[name] = value
def __getitem__(self, key):
return self.list[key]
def __setitem__(self, key, value):
self.list[key] = value
def __getslice__(self, i, j):
return self.list[i : j]
def __setslice__(self, i, j, s):
self.list[i : j] = s
def __contains__(self, obj):
if obj in self.list:
return True
else:
return False
There must be a way to inherit from the list type without having to
redefine all the methods and attributes that regular lists have.
i.e.
class Point(list):
...
Can someone provide an example?
Thanx in advance