Python3:访问对象的父类属性

2024-05-20 18:46:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图访问对象的父类“getter”属性,并将其作为函数参数传递。问题是它是从“getter”传递值,而不是从getter函数本身传递值。我希望能够将此函数传递到另一个类中,并在每次调用时获得更新的值

例如,如果传递getter函数时返回的值是77,则传递的是值77,而不是函数本身。目标是传递返回当前值而不是第一次传递时的值的函数

我尝试在对象的__dict__中查找属性,但它只显示子类而不是基类的方法等。我尝试使用super作为访问此文件的方式,但无法确定这是否是正确的路径

################### Class definitions from library ###################
# The parent class from the library
class Adafruit_BME280():
     # ... Removed Code ...
     @property
     def temperature(self):
          self._read_temperature()
          return self._t_fine / 5120.0

# The child class from the library
class Adafruit_BME280_I2C(Adafruit_BME280):
     # ... Removed Code ...

################### My Code ###################
# My new class that is passed a function to get temperature
class TempSensor:
     def __init__(self, get_temperature_func):
          self.get_temperature = get_temperature_func

     def print_temperature():
          print(self.get_temperature)

# My main function where the object is created
def main():
     bme280 = Adafruit_BME280_I2C()
     temp_sensor = TempSensor(bme280.temperature)
     temp_sensor.print_temperature
# 

在上面给出的代码中,如果创建TempSensor对象时温度为77.0度,则调用temp_sensor.print_temperature时总是打印77.0度,而不是当前温度


Tags: the对象函数fromselfadafruitgetdef