开发者

In python, is there a setdefault() equivalent for getting object attributes?

开发者 https://www.devze.com 2022-12-13 20:57 出处:网络
Python\'s setdefault allows you to get a value from a dictionary, but if the key doesn\'t exist, then you开发者_如何学编程 assign the based on parameter default.You then fetch whatever is at the key i

Python's setdefault allows you to get a value from a dictionary, but if the key doesn't exist, then you开发者_如何学编程 assign the based on parameter default. You then fetch whatever is at the key in the dictionary.

Without manipulating an object's __dict__Is there a similar function for objects?

e.g.

I have an object foo which may or may not have attribute bar. How can I do something like:

result = setdefaultattr(foo,'bar','bah')


Note that the currently accepted answer will, if the attribute doesn't exist already, have called hasattr(), setattr() and getattr(). This would be necessary only if the OP had done something like overriding setattr and/or getattr -- in which case the OP is not the innocent enquirer we took him for. Otherwise calling all 3 functions is gross; the setattr() call should be followed by return value so that it doesn't fall through to return getattr(....)

According to the docs, hasattr() is implemented by calling getattr() and catching exceptions. The following code may be faster when the attribute exists already:

def setdefaultattr(obj, name, value):
    try:
        return getattr(obj, name)
    except AttributeError:
        setattr(obj, name, value)
    return value


Python doesn't have one built in, but you can define your own:

def setdefaultattr(obj, name, value):
    if not hasattr(obj, name):
        setattr(obj, name, value)
    return getattr(obj, name)


vars(obj).setdefault(name, value)


Don't Do This.

Please use __init__ to provide default values. That's the Pythonic way.

class Foo( object ):
    def __init__( self ):
        self.bar = 'bah'

This is the normal, standard, typical approach. There's no compelling reason to do otherwise.

0

精彩评论

暂无评论...
验证码 换一张
取 消