I am new in Python and in OOP in general. I have an error "...instance has no attribute '__getitem__'", and I understand that the object I have created is not a list. How can I make to be a list object. Here is the class file:
#!/usr/bin/python -tt
import math, sys, matrix, os
class Point:
'Class for points'
pointCount = 0
def __init__(self, x, y, z):
'initialise the Point from three coordinates'
self.x = x
self.y = y
self.z = z
Point.pointCount += 1
def __str__(self):
'print the Point'
return 'Point (%f, %f, %f)' %(self.x, self.y, self.z)
def copyPoint(self, distance):
'create another Point at distance from the self Point'
return Point(self.x + distance[0], self.y + distance[1], self.z + distance[2])
def __del__(self):
'delete the Point'
Point.pointCount -= 1
#print Point.pointCount
return '%s deleted' %self
I need to have it as a point with three coordinates inside (x, y, z), and those coordinates must be “callable” like in a list instance with [].
I have read similar topics but did not understand much. Please describe it in simple words and with examples.
I suggest you consider making your Point class using the collections.namedtuple factory function which will make it a subclass of the the built-in
tupleclass. This will save you some boiler-plate work.namedtupleclass have attributes that can be accessed both by name, such asp.xand indexed, likep[0].They are also very memory efficient like
tuples, which may be important if you’re going to have a lot of class instances.You can further specialize what is returned by subclassing it, or use the
verboseoption to capture the source code and modify that as necessary.There’s an example in the documentation linked to above showing it being used to create a 2D
Pointclass, which seems like it could be very helpful in your specific use-case.Here’s an example showing how one could define a custom 3D Point class via subclassing:
Output:
Note that by using
namedtupleyou don’t have to implement a__getitem__()yourself, nor write a__str__()method. The only reason an__init__()was needed was because of the need to increment the class instance counter which was added — something thatnamedtuples don’t have or do by default.