setattr

exec to add a function into a class

跟風遠走 提交于 2019-12-01 10:58:54
So I've looked at similar questions, and I've found some solutions to this, but I can't quite figure out how to do this. What I'm trying to do is add a method to a class from a string. I can do this with the setattr() method, but that won't let me use self as an attribute in the extra method. Here's an example: (and I apologize for the variable names, I always use yolo when I'm mocking up an idea) class what: def __init__(self): s = 'def yolo(self):\n\tself.extra = "Hello"\n\tprint self.extra' exec(s) setattr(self,"yolo",yolo) what().yolo() returns this: Traceback (most recent call last): File

What's the difference between setattr() and object.__setattr__()?

与世无争的帅哥 提交于 2019-11-30 08:19:49
问题 I know that you can't call object.__setattr__ on objects not inherited from object , but is there anything else that is different between the two? I'm working in Python 2.6, if this matters. 回答1: Reading this question again I misunderstood what @paper.cut was asking about: the difference between classic classes and new-style classes (not an issue in Python 3+). I do not know the answer to that. Original Answer * setattr(instance, name, value) is syntactic sugar for instance.__setattr__(name,

How do I properly override __setattr__ and __getattribute__ on new-style classes in Python?

给你一囗甜甜゛ 提交于 2019-11-30 06:26:00
问题 I want to override my Python class's __getattribute__ and __setattr__ methods. My use case is the usual one: I have a few special names that I want to handle, and I want the default behavior for anything else. For __getattribute__ , it seems that I can request the default behavior simply by raising AttributeError . However, how can I achieve the same in __setattr__ ? Here is a trivial example, implementing a class with immutable fields "A", "B", and "C". class ABCImmutable(SomeSuperclass):

What's the difference between setattr() and object.__setattr__()?

▼魔方 西西 提交于 2019-11-29 06:34:21
I know that you can't call object.__setattr__ on objects not inherited from object , but is there anything else that is different between the two? I'm working in Python 2.6, if this matters. Reading this question again I misunderstood what @paper.cut was asking about: the difference between classic classes and new-style classes (not an issue in Python 3+). I do not know the answer to that. Original Answer * setattr(instance, name, value) is syntactic sugar for instance.__setattr__(name, value) ** . You would only need to call object.__setattr__(...) inside a class definition, and then only if

How do I properly override __setattr__ and __getattribute__ on new-style classes in Python?

那年仲夏 提交于 2019-11-28 19:07:51
I want to override my Python class's __getattribute__ and __setattr__ methods. My use case is the usual one: I have a few special names that I want to handle, and I want the default behavior for anything else. For __getattribute__ , it seems that I can request the default behavior simply by raising AttributeError . However, how can I achieve the same in __setattr__ ? Here is a trivial example, implementing a class with immutable fields "A", "B", and "C". class ABCImmutable(SomeSuperclass): def __getattribute__(self, name): if name in ("A", "B", "C"): return "Immutable value of %s" % name else:

getattr and setattr on nested subobjects / chained properties?

这一生的挚爱 提交于 2019-11-28 17:19:34
问题 I have an object ( Person ) that has multiple subobjects ( Pet, Residence ) as properties. I want to be able to dynamically set the properties of these subobjects like so: class Person(object): def __init__(self): self.pet = Pet() self.residence = Residence() class Pet(object): def __init__(self,name='Fido',species='Dog'): self.name = name self.species = species class Residence(object): def __init__(self,type='House',sqft=None): self.type = type self.sqft=sqft if __name__=='__main__': p

Using setattr() in python

不羁岁月 提交于 2019-11-28 04:37:49
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 Way, ex42 —the while loop @ lines 18-41. I tried writing an \__init__() , and using getattr() instead,

Why does setattr fail on a bound method

僤鯓⒐⒋嵵緔 提交于 2019-11-27 13:15:16
In the following, setattr succeeds in the first invocation, but fails in the second, with: AttributeError: 'method' object has no attribute 'i' Why is this, and is there a way of setting an attribute on a method such that it will only exist on one instance, not for each instance of the class? class c: def m(self): print(type(c.m)) setattr(c.m, 'i', 0) print(type(self.m)) setattr(self.m, 'i', 0) Python 3.2.2 The short answer: There is no way of adding custom attributes to bound methods. The long answer follows. In Python, there are function objects and method objects . When you define a class,

How can I dynamically create class methods for a class in python [duplicate]

时光毁灭记忆、已成空白 提交于 2019-11-27 10:51:10
This question already has an answer here: Adding a Method to an Existing Object Instance 16 answers If I define a little python program as class a(): def _func(self): return "asdf" # Not sure what to resplace __init__ with so that a.func will return asdf def __init__(self, *args, **kwargs): setattr(self, 'func', classmethod(self._func)) if __name__ == "__main__": a.func I receive the traceback error Traceback (most recent call last): File "setattr_static.py", line 9, in <module> a.func AttributeError: class a has no attribute 'func' What I am trying to figure out is, how can I dynamically set

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

一曲冷凌霜 提交于 2019-11-26 17:09:53
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. import sys thismodule = sys.modules[__name__] setattr(thismodule, name, value) or, without using setattr (which breaks the letter of the question but satisfies