Python Forum
dynamic use of attributes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dynamic use of attributes
#4
If you just want something you can assign any attribute to, subclass object:

>>> class Foo(object):
...     pass
...
>>> foo = Foo()
>>> foo.bar = 5
>>> foo.bar
5
Oddly enough, this doesn't work with object itself:

>>> obj = object()
>>> obj.bar = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'bar'
Another handy one creates and assigns any attributes you pass it:

class Morphling(object):

    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
>>> morph = Morphling(foo = 5)
>>> morph.foo
5
I use that type of class to make dummy objects for unit testing.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
dynamic use of attributes - by Skaperen - Oct-18-2018, 03:49 AM
RE: dynamic use of attributes - by Gribouillis - Oct-18-2018, 05:29 AM
RE: dynamic use of attributes - by Skaperen - Oct-18-2018, 08:41 PM
RE: dynamic use of attributes - by ichabod801 - Oct-19-2018, 03:12 AM
RE: dynamic use of attributes - by Skaperen - Oct-19-2018, 06:00 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020