Wednesday, 19 August 2015

Python per instance properties?


kinda new python programming, bear me here if i'm asking obvious. i've done cursory web search on topic , can't find answer, may mean i'm searching wrong thing...

possible define properties on per-instance basis? example, i'd define position class can created in either cartesian or spherical coordinates. in cartesian case, i'd store (x,y,z) , calculate (r,az,el) on fly. in spherical case, i'd store (r,az,el) , calculate (x,y,z) on fly.

1 way this, obviously, class hierarchy-- create position class, spherical , cartesian subclasses.

leads problems in defining pose. pose sort of directed position-- both position , orientation. such, i'd subclass position, don't want have create both cartesianpose , sphericalpose. instead wrap position , orientation, need whole slew of property definitions nothing expose enclosed position , orientation attributes.

this:

code:
      def __init__(self,a=0,b=0,c=0,format='cartesian'):          if(format=='cartesian'):              self.x=a              self.y=b              self.z=c              self.r=property(getr,setr)              self.az=property(getaz,setaz)              self.el=property(getel,setel)          elif(format=='spherical'):              self.r=a              self.az=b              self.el=c              self.x=property(getx,setx)              self.y=property(gety,sety)              self.z=property(getz,setz)          else:               #add other formats or raise exception  
i may not have quite right, idea. doesn't work, of course, because need set:
code:
self.__cls__.x=property(...)
which works, long every position everywhere follows same format, because i've tweaked class everyone. kind of defeats purpose.

there way @ instance level? i'm sure there's hundred ways of working around this-- i'm implementing 1 now-- ideally i'd able without putting if/else in every getter:

code:
  a=position(1,2,3,format='cartesian')  print(a.x)  print(a.az)    b=position(5,pi/4,0,format='spherical')  print(b.x)  print(b.az)  
 



Forums Macs Mac Programming


  • iPhone
  • Mac OS & System Software
  • iPad
  • Apple Watch
  • Notebooks
  • iTunes
  • Apple ID
  • iCloud
  • Desktop Computers
  • Apple Music
  • Professional Applications
  • iPod
  • iWork
  • Apple TV
  • iLife
  • Wireless

No comments:

Post a Comment