プログラミングなど

2009年6月12日金曜日

pythonでプロパティ

pythonでプロパティを使用する例。

---- コード ----

# -*- coding: utf-8 -*-

class Coordinate:
  _coord = [0.0, 0.0, 0.0] # x, y, z

  def __init__(self, x = 0.0, y = 0.0, z = 0.0):
    self._coord[0], self._coord[1], self._coord[2] = x, y, z

  def getx(self):
    return self._coord[0]
  def setx(self, value):
    self._coord[0] = value
  x = property(getx, setx)
  def gety(self):
    return self._coord[1]
  def sety(self, value):
    self._coord[1] = value
  y = property(gety, sety)
  def getz(self):
    return self._coord[2]
  def setz(self, value):
    self._coord[2] = value
  z = property(getz, setz)

coord = Coordinate(11.2, 12.3)
coord.x = 15.0
coord.y = 12.8

if __name__ == "__main__":
  print coord.x, coord.y, coord.z

# end of file

0 件のコメント:

コメントを投稿