setattr

Using setattr() in python

左心房为你撑大大i 提交于 2019-11-26 15:44:30
问题 I am looking for someone to explain the basics of how to use, and not use setattr() . My problem arose trying to use one class method/function to return data that is then put in another method/function. Perhaps a simpler approach would be much better in this case, but I'm trying to understand how classes work/are used. This problem seems to hinge on setattr() , and this is my attempt to make a fairly simple use of this. Though it's not quite the same problem, I was following Python The Hard

How to use __setattr__ correctly, avoiding infinite recursion

微笑、不失礼 提交于 2019-11-26 12:45:53
问题 I want to define a class containing read and write methode, which can be called as follows: instance.read instance.write instance.device.read instance.device.write To not use interlaced classes, my idea was to overwrite the __getattr__ and __setattr__ methods and to check, if the given name is device to redirect the return to self . But I encountered a problem giving infinite recursions. The example code is as follows: class MyTest(object): def __init__(self, x): self.x = x def __setattr__

How do I call setattr() on the current module?

别等时光非礼了梦想. 提交于 2019-11-26 05:17:14
问题 What do I pass as the first parameter \" object \" to the function setattr(object, name, value) , to set variables on the current module? For example: setattr(object, \"SOME_CONSTANT\", 42); giving the same effect as: SOME_CONSTANT = 42 within the module containing these lines (with the correct object ). I\'m generate several values at the module level dynamically, and as I can\'t define __getattr__ at the module level, this is my fallback. 回答1: import sys thismodule = sys.modules[__name__]