Al369Tesla
Al369Tesla

Reputation: 13

A method inside a class that calls another method

I need help with the below code. I want to use the get_skies, get_high, and get_low method to call the set_skies, set_high, and set_low methods, respectively, and then return the value for init_skies, init_high, and init_low, respectively.

This is what I have got so far:

class WeatherForecast():
  def set_skies(self, init_skies):
     return init_skies

  def set_high(self, init_high):
     return init_high

  def set_low(self, init_low):
     return init_low

  def get_skies(self):
    self.set_skies()

  def get_high(self):
    self.set_high()

  def get_low(self):
    self.set_low()

Upvotes: 0

Views: 51

Answers (1)

Shubham Sharma
Shubham Sharma

Reputation: 71707

In python attributes of class are publically accessible. You don't need to use getter or setters for attributes unless you want to perform some kind of preprocessing or mutation of the attribute

In your case, you can try this,

class WeatherForecast():
    def __init__(self, init_skies, init_low, init_high):
        self._init_skies = init_skies
        self._init_low = init_low
        self._init_high = init_high

    @property
    def skies(self):
        return self._init_skies

    @property
    def high(self):
        return self._init_high

    @property
    def low(self):
        return self._init_low

    @skies.setter
    def skies(self, value):
        self._init_skies = value

    @high.setter
    def high(self, value):
        self._init_high = value

    @low.setter
    def low(self, value):
        self._init_low = value

w = WeatherForecast(1, 2, 3)
print(w.skies, w.low, w.high) # --> print the values

# Set the values
w.skies = 10
w.low = 20
w.high = 30

print(w.skies, w.low, w.high) # -->  print the updated values

Upvotes: 2

Related Questions