0
class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def radius(self):
        return self.diameter / 2.0

    @radius.setter
    def radius(self, radius):
        self.diameter = radius * 2.0


foo = Circle(5)
print(foo.radius)

Sorry if I am asking this in the wrong way. The above code (from Raymond Hettinger's talk) runs perfectly fine. However, I cannot understand how/when the setter is actually being called, or how it is receiving "radius" variable to set the diameter.

I thought that for a setter must be called with parameter, e.g. self.radius(radius), or from outside the class, foo.radius(radius)

Here it must be the case that the setter is accessing the radius parameter passed from outside the class and assigning it to diameter.

  • That's what a property setter is: a function called when you try to set the radius, e.g. where it says `self.radius = radius`. – khelwood Nov 06 '21 at 19:40
  • When you instantiate `foo` the `__init__` method is executed and inside it is `self.radius = radius`. That is when the setter is called. – buran Nov 06 '21 at 19:42
  • Wow I must be a moron. So the ONLY syntax for utilizing the @setter, is as folows: foo.radius = somenumber and foo.radius(somenumber) is NOT a thing Yep, just tested it. I must have brought some residual java over. My deepest apologies guys. – mdlphx92 Nov 06 '21 at 19:45
  • As you mention Java, note that in typical case you will not need getters and setters – buran Nov 06 '21 at 19:49

0 Answers0