Could you tell me how Python's standard feature allows you to set properties under any name?
I would like to do the following, but do I have to create my own class?
I'd like to know another smart way.
classMyObject():#← Don't bother to create your own class, you want to set properties freely like dict.
pass
obj=MyObject()
obj.x = 'AA'
obj.y = 'BB'
obj.z = 'CC'
print(obj.x, obj.y, obj.z)
dict requires key brackets to specify properties.
The namedtuple must specify configurable properties in advance.
import types
obj=types.SimpleNamespace()
obj.x = 'AA'
obj.y = 'BB'
obj.z = 'CC'
print(obj.x, obj.y, obj.z)#AA BBCC
As a mental exercise, you can create your own class of objects in one line without class definition (creating but not constraining variables):
obj=type("NameSpace", (object,), {})()
class type(name, bases, dict, **kwds)
or
IPython7.31.1 -- An enhanced interactive Python.Type '?' for help.
In[1]—X=type('X', (), dict(x='A', y='B', z='C')))
In[2]: X
Out[2]—_main__.X
In[3]: X.x, X.y, X.z
Out[3]: ('A', 'B', 'C')
In[4]: obj=X()
In [5]: [a for a indir(obj) if not a.startswith('_')]
Out [5]: ['x', 'y', 'z']
In[6]: {a:getattr(obj,a)for a indir(obj)if not a.startwith('_')}
Out[6]: {'x': 'A', 'y': 'B', 'z': 'C'}
In [7]:
In addition,
Namespace
or
argparse
In[7]:from argparse import Namespace
In[8]:o=Namespace(bar='BAR', foo=True)
In[9]: o.bar
Out [9]: 'BAR'
In[10]:o
Out [10]—Namespace (bar='BAR', foo=True)
In [11]:
© 2025 OneMinuteCode. All rights reserved.