How can I create an object and add attributes to it?

前端 未结 16 1692
长情又很酷
长情又很酷 2020-11-28 00:36

I want to create a dynamic object (inside another object) in Python and then add attributes to it.

I tried:

obj = someobject
obj.a = object()
setattr         


        
16条回答
  •  醉梦人生
    2020-11-28 01:07

    Coming to this late in the day but here is my pennyworth with an object that just happens to hold some useful paths in an app but you can adapt it for anything where you want a sorta dict of information that you can access with getattr and dot notation (which is what I think this question is really about):

    import os
    
    def x_path(path_name):
        return getattr(x_path, path_name)
    
    x_path.root = '/home/x'
    for name in ['repository', 'caches', 'projects']:
        setattr(x_path, name, os.path.join(x_path.root, name))
    

    This is cool because now:

    In [1]: x_path.projects
    Out[1]: '/home/x/projects'
    
    In [2]: x_path('caches')
    Out[2]: '/home/x/caches'
    

    So this uses the function object like the above answers but uses the function to get the values (you can still use (getattr, x_path, 'repository') rather than x_path('repository') if you prefer).

提交回复
热议问题