Python class property and class constants -


i'm trying work "getters" , "setters" in python classes. have simple rectangle class defined below each rectangle object has class variables length , width defined. there class constant called sides knows number of sides of particular shape. now, when run class, works fine. can like

>>> rect = rectangle(2,3) >>> rect.length 2 >>> rect.width 3 

however, if try have print out class constant sides, returns this

>>> rect.sides <property object @ 0x037f6c90> 

rather returning value 4. how can return value? on potentially related note, tried having property method sides variable defined such

@property def sides(self):     return self._sides 

this works other object variables, when attempt access sides through method, error saying rectangle has no attribute _sides. reference sides self.__class__.sides proper?

rectangle class

import abc shape import shape  class rectangle(shape):      sides = 4      def __init__(self, length, width):         super().__init__('rectangle')         self.length = length         self.width = width      #the getters     @property     def sides(self):         return self.__class__.sides      @property     def length(self):         return self._length      @property     def width(self):         return self._width      #the setters      @sides.setter     def sides(self, value):         if value != 4:             raise valueerror('error: cannot set number of sides value '                              'other 4.')         self._sides = value      @length.setter     def length(self, value):         if value <= 0:             raise valueerror('error: length must positive.')         self._length = value      @width.setter     def width(self, value):         if value <= 0:             raise valueerror('error: width must positive.')         self._width = value        def getarea(self):         return self.length * self.width 

you should -

#the getters @property def sides(self):     return self.__class__._sides 

instead of -

#the getters @property def sides(self):     return self.__class__.sides 

notice _sides

also, @ start of class think wanted initialize _sides instead of sides.

you need use different name sides because sides used refer class property, if try return self.__class__.sides directly return property object, can use type(rect.sides) in example , not work, check type is.

also, note, instead of self.__class__.sides , if return self.sides , inside getter function, keep on recursively calling getter function causing python error out -

runtimeerror: maximum recursion depth exceeded while calling python object


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -