setattr

How can I reach a private variable within the object

一曲冷凌霜 提交于 2019-12-31 01:50:08
问题 I would like to modify an object private variable class Example(): __myTest1 = 1 __myTest2 = 1 def __init__(self): pass def modifyTest(self, name = 'Test1', value): setattr(self, '__my'+name, value); I tried the code above and it's seems that not possible to reach a private variable, AttributeError: Example instance has no attribute '__myTest1' Is there any way to modify a private variable? 回答1: Accessing from outside: e = Example() e._Example__myTest1 # 1 Due to private variable name

exec to add a function into a class

删除回忆录丶 提交于 2019-12-30 11:15:03
问题 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 to add a function into a class

吃可爱长大的小学妹 提交于 2019-12-30 11:15:00
问题 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

Implementing a dict-like object with __getattr__ and __setattr__ functionality

安稳与你 提交于 2019-12-24 00:46:20
问题 I'm trying to implement a dict -like object which can be accessed/modified with __getattr__ and __setattr__ for ease of use for my users. The class also implements some other simple functionality. Using this answer as a template, my implementation is currently as follows: from collections import MutableMapping class Dictish (MutableMapping): """ A dict-like mapping object. vals are always coerced to str. Should provide __getattr__ and __setattr__ as aliases for __getitem__ and __setitem__. ""

Why does setattr fail on a bound method

与世无争的帅哥 提交于 2019-12-17 10:51:06
问题 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 回答1: The short answer: There is no way of adding custom attributes to bound methods.

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

孤人 提交于 2019-12-17 10:15:38
问题 This question already has answers here : Adding a Method to an Existing Object Instance (16 answers) Closed last year . 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

__setattr__ versus __slots__ for constraining attribute creation in Python

霸气de小男生 提交于 2019-12-14 02:29:24
问题 I've been reading about how make Python classes less dynamic, specifically by not allowing users to dynamically create new attributes. I've read that overloadding __setattr__ is a good way to do this , and __slots__ is not the way to go. One post on this last thread actually suggests that __slots__ can break pickling. (Can anyone confirm this?) However, I was just reading the whatsnew for Python 2.2, and the attribute access section actually suggests using __slots__ for the very purpose of

need a simple way to add meta information/class to a python list/tuple variable?

℡╲_俬逩灬. 提交于 2019-12-10 19:34:16
问题 All, I want simple meta information to be enclosed on an list object, see below code. >>> a = [] >>> a.foo = 100 Traceback (most recent call last): File "<interactive input>", line 1, in <module> AttributeError: 'list' object has no attribute 'foo' >>> setattr(a,"foo",100) Traceback (most recent call last): File "<interactive input>", line 1, in <module> AttributeError: 'list' object has no attribute 'foo' >>> dir(a) ... '__setattr__', '__setitem__', ... my quesions are why I can not use

Python - how can I dynamically remove a method from a class — i.e. opposite of setattr

▼魔方 西西 提交于 2019-12-09 10:58:16
问题 I don't know if I have a good design here, but I have a class that is derived from unittest.TestCase and the way I have it set up, my code will dynamically inject a bunch of test_* methods into the class before invoking unittest to run through it. I use setattr for this. This has been working well, but now I have a situation in which I want to remove the methods I previously injected and inject a new set of methods. How can I remove all the methods in a class whose names match the pattern

python setattr for dynamic method creator with decorator

大憨熊 提交于 2019-12-08 02:25:47
问题 I have a class which has multiple methods defined. import mat class Klass(object): @mat.sell(mat.CanSet): def method1(self): return None @mat.sell(mat.CanSet): def method2(self): return 'value2' Imagine I have 10 methods that I need to populate for this 'Klass'. I want to generate these methods without explicitely writing them all. So I want to do a factory that does setattr for each method. Problem is that I do following and the last method has the last value. Each do not get its related