简体   繁体   中英

Python TypeError: 'int' object is not callable in OOP

I have a problem. I learn of using setters in python. I have some code down here and I try to use method measure_set which doesn't work because I have a TypeError: 'int' object is not callable . Can someon explain me why this is happens? I tried to find solution but I didin't find a similar problem in OOP with using setters. Thanks, and have a nice day.

class Sensor:
    def __init__(self, location, _measurement = 0, _precision = float('inf'), _unit = 'N/A'):
        self._measurement = _measurement
        self._precision = _precision
        self._unit = _unit
        self.location = location
        self.log = []

    @property
    def log_average(self):
        return sum(self.log)/len(self.log)

    @property
    def measurement(self):
        return self._measurement

    @measurement.setter
    def measure_set(self, measure):
        self._measurement = measure
        self.log.append(self._measurement)

    @property
    def description(self):
        return f'{self._measurement} +/- {self._unit}'

if __name__ == '__main__':
    s = Sensor('Ostatni Grosz')
    print(s.description)
    s.measure_set(10)
    s.measure_set(20)
    print(s.log)
    print(s.log_average)

The name of the setter should match the name of the property.

@measurement.setter
def measurement(self, measure):
    self._measurement = measure
    self.log.append(self._measurement)

because the property instance returned by measurement.setter is assigned to the name measurement . With your code, you now have two separate properties, one (read-only) property named measurement and one named measurement_set .

The setter isn't meant to be called directly (and can't, because the name no longer refers to a callable object, but to the property). When you write self.measurement_set(10) , the attribute access self.measurement_set returns (via the getter) the current int value of self._measurement , then tries to call that with an argument of 10.

Instead, you just assign to the property directly, which triggers the invocation of the setter.

s.measurement = 10
s.measurement = 20 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM