Jak programowo ustawić atrybut?
Załóżmy, że mam obiekt Pythona x
i łańcuch s
, Jak ustawić atrybut s
na x
? Więc:
>>> x = SomeObject()
>>> attr = 'myAttr'
>>> # magic goes here
>>> x.myAttr
'magic'
Co to za Magia? Celem tego, nawiasem mówiąc, jest buforowanie wywołań do x.__getattr__()
. 153
3 answers
setattr(x, attr, 'magic')
O pomoc:
>>> help(setattr)
Help on built-in function setattr in module __builtin__:
setattr(...)
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.
Edit: należy jednak zauważyć (jak zaznaczono w komentarzu), że nie można tego zrobić dla "czystej" instancji object
. Ale jest prawdopodobne, że masz prostą podklasę obiektu, w której będzie działać dobrze. Nalegam, By O. P. nigdy nie tworzyło takich obiektów.
227
Author: Ali Afshar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-01 23:06:38
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-01 23:06:38
Zazwyczaj definiujemy dla tego klasy.
class XClass( object ):
def __init__( self ):
self.myAttr= None
x= XClass()
x.myAttr= 'magic'
x.myAttr
Można jednak, do pewnego stopnia, zrobić to za pomocą wbudowanych funkcji setattr
i getattr
. Jednak nie działają one bezpośrednio na instancjach object
.
>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'
Pracują jednak na wszelkiego rodzaju prostych klasach.
class YClass( object ):
pass
y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr
45
Author: S.Lott,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-26 04:45:46
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-26 04:45:46
Niech X będzie obiektem wtedy można to zrobić na dwa sposoby
x.attr_name = s
setattr(x, 'attr_name', s)
15
Author: vijay shanker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-28 14:37:59
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-28 14:37:59