I wrote a code that simulates the use of abc
module and properties
. However, it seems that I couldn't be able to access width
and height
variables. The code is as the following:
from abc import ABCMeta, abstractmethod
class Polygon:
__metaclass__ = ABCMeta
@abstractmethod
def compute_area(self): pass
def __init__(self):
self.width = None
self.height = None
@property
def width_prop(self):
return self.width
@property
def height_prop(self):
return self.height
@width_setter.setter
def width_setter(self, width):
self.width = width
@height_setter.setter
def height_setter(self, height):
self.height = height
class Triangle(Polygon):
def compute_area(self):
return 0.5 * width * height
if __name__ == "__main__":
tri = Triangle()
tri.height_setter(20)
tri.width_setter(30)
print "Area of the triangle = ", tri.compute_area()
The error message that I obtained is NameError: name 'width_setter' is not defined
. What could be wrong in my implementation?
EDIT:
from abc import ABCMeta, abstractmethod
class Polygon:
__metaclass__ = ABCMeta
@abstractmethod
def compute_area(self): pass
def __init__(self):
self.width = None
self.height = None
@property
def width_prop(self):
return self.width
@width_prop.setter
def width_setter(self, width):
self.width = width
@property
def height_prop(self):
return self.height
@height_prop.setter
def height_setter(self, height):
self.height = height
class Triangle(Polygon):
def compute_area(self):
return 0.5 * self.width * self.height
if __name__ == "__main__":
tri = Triangle()
tri.height_prop = 20
tri.width_prop = 30
print "Area of the triangle = ", tri.compute_area()
edit: In such simple case like example use direct variable access. See Ned Batchelder's answer.
If you need extra functionality when accessing variables you can use this.
http://docs.python.org/library/functions.html#property
from abc import ABCMeta, abstractmethod
class Polygon(object):
__metaclass__ = ABCMeta
@abstractmethod
def compute_area(self):
pass
def __init__(self):
self._width = None
self._height = None
@property
def width(self):
getting_variable_value()
return self._width
@width.setter
def width(self, width):
setting_variable_value()
self._width = width
@property
def height(self):
getting_variable_value()
return self._height
@height.setter
def height(self, height):
setting_variable_value()
self._height = height
class Triangle(Polygon):
def compute_area(self):
return 0.5 * self.width * self.height
if __name__ == "__main__":
tri = Triangle()
tri.height = 20
tri.width = 30
print "Area of the triangle = ", tri.compute_area()