4 python list object magic-methods
我是Python的新手,也是OOP的新手.我有一个错误"...instance has no attribute '__getitem__'",我知道我创建的对象不是列表.我怎样才能成为列表对象.这是类文件:
#!/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
Run Code Online (Sandbox Code Playgroud)
我需要将它作为一个在(x,y,z)内有三个坐标的点,并且那些坐标必须是"可调用的",就像在带有[]的列表实例中一样.
我读过类似的主题,但不太了解.请用简单的单词和例子来描述.
写一个__getitem__方法:
def __getitem__(self, item):
return (self.x, self.y, self.z)[item]
Run Code Online (Sandbox Code Playgroud)
这构造了一个tuplex,y和z,并使用Python自己的索引工具来访问它.
或者,您可以将自己的内部存储切换为元组,并为x,y和z创建属性:
def __init__(self, x, y, z):
self.coords = (x, y, z)
@property
def x(self): # sim. for y, z
return self.coords[0]
def __getitem__(self, item):
return self.coords[item]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6569 次 |
| 最近记录: |