python - 类中调用另一个方法的方法
问题描述
我需要以下代码的帮助。我想用get_skies
, get_high
, 和get_low
方法分别调用set_skies
, set_high
, 和方法,然后分别返回, , 和set_low
的值。init_skies
init_high
init_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 中,类的属性是可公开访问的。 除非您想对属性执行某种预处理或突变,否则您不需要对属性使用 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
推荐阅读
- python - 将此元组列表转换为字典
- c# - 如何在有 HttpGetAttribute 的地方添加 HttpHeadAttribute?
- html - 结合 rowspan 和 colspan 的引导程序
- docker - 我怎样才能让我的容器从开始 -> 健康
- java - 如何将 .aar 包的所有内容转换为 .jar 包?
- excel - 从excel工作簿自动创建csv文件
- github - 如何从 master 以外的分支运行 GitHub Action?
- performance - 英特尔 LLC 的一些奇怪行为
- python - 在不使用的情况下构建 django detailview 和 listview
- snowflake-cloud-data-platform - 计算雪花中数据库的数据存储