简体   繁体   中英

call a property setter dynamically

self.__dict__.update resp. self.__dict__.... is overwriting the serial setter function:

class Overwrite:
  serial_ = None

  @property
  def serial(self):
    print("get serial...")
    return self.serial_

  @serial.setter
  def serial(self, v):
    print("set serial...")
    self.serial_ = v

  def demo(self):
    test = {'serial': 'D1D297C1E8839EF2C0E69EF709653C05'}
    self.__dict__.update(test)


ow = Overwrite()
ow.demo()
print(ow.serial)

I would like to find a way to set the serial setter function dynamically. Can someone help me?

You can use setattr :

for k, v in test.items():
    setattr(self, k, v)

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