python 2.7 - Ways to set default value for class attribute without using hasattr -
i have set attribute class instance in case if doesn't exist. using code below achieve that:
class o(object): pass o = o() if not hasattr(o, 'some_attr'): setattr(o, 'some_attr', none) print o.some_attr
is there better way perform such action ?
classes , instances has own namespace represented pre-defined __dict__
attribute dictionary, method setdefault used instead of if hasattr -> setattr
flow add new attribute class instance:
class o(): pass o = o() o.__dict__.setdefault('some_attr', none) print o.some_attr
method sugggested @martijnpieters:
also access __dict__
attribute vars function , call setdefault
method in code sample above:
vars(o).setdefault('some_attr', none) print o.some_attr
Comments
Post a Comment