首页 > 解决方案 > 类中调用另一个方法的方法

问题描述

我需要以下代码的帮助。我想用get_skies, get_high, 和get_low方法分别调用set_skies, set_high, 和方法,然后分别返回, , 和set_low的值。init_skiesinit_highinit_low

这是我到目前为止所得到的:

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()

标签: python

解决方案


在 python 中,类的属性是可公开访问的。 除非您想对属性执行某种预处理或突变,否则您不需要对属性使用 getter 或 setter

在你的情况下,你可以试试这个,

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

推荐阅读