解析一下下面的python代码?
PHP中文网
PHP中文网 2017-04-17 17:29:56
0
2
362

近日在学习python,看的的廖大的python教程,这里有段代码看不懂
主要是getValueOrDefault()函数 谁给剖析一下?

class Model(dict, metaclass=ModelMetaclass):

    def __init__(self, **kw):
        super(Model, self).__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Model' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

    def getValue(self, key):
        return getattr(self, key, None)

    def getValueOrDefault(self, key):
        value = getattr(self, key, None)
        if value is None:
            field = self.__mappings__[key]
            if field.default is not None:
                value = field.default() if callable(field.default) else field.default
                logging.debug('using default value for %s: %s' % (key, str(value)))
                setattr(self, key, value)
        return value
PHP中文网
PHP中文网

认证0级讲师

reply all(2)
刘奇

It seems that this is a database model base class, which inherits from dict, so it can be said to be a dictionary. In addition, you can take a look at __mappings__ in ModelMetaclass, which is a mapping of attribute names to columns. So getValueOrDefault is easy to understand. It is to get the value of a certain attribute. If the attribute of the object has not been assigned a value, get the default value of its corresponding column. For example, the following Model represents a user:

class UserModel(Model):
    name = Column(String, default='kyle')
    age = Column(Int, default=15)
    
# 假设我们现在有一个 UserModel 的对象
user = UserModel()

# 以下两种方式是等价的,都是去访问 name 属性,或者说 name 列的值
# 注意:还没有赋值,所以会 AttributeError
user.name
user['name']

# 下面的 getValueOrDefault 则可以返回 name 的默认值 'kyle'

user. getValueOrDefault('name')

Note: The above code is similar to pseudo code and cannot be run directly. It is only used for auxiliary explanation.

PHPzhong
class Model(dict, metaclass=ModelMetaclass):
    # 初始化, 没啥好说的
    def __init__(self, **kw):
        super(Model, self).__init__(**kw)
    # 如果取不到值, 报错, 这是一个魔术方法, 使用时直接getattr(obj, key)
    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Model' object has no attribute '%s'" % key)
    # 同魔术方法, 设置一个值, 使用时setattr(obj, key, val)
    def __setattr__(self, key, value):
        self[key] = value
    # 类方法, 获取一个值
    def getValue(self, key):
        return getattr(self, key, None)
    # 类方法, 获取一个值或其默认值
    def getValueOrDefault(self, key):
        value = getattr(self, key, None)
        if value is None:
            field = self.__mappings__[key]
            if field.default is not None:
                value = field.default() if callable(field.default) else field.default
                logging.debug('using default value for %s: %s' % (key, str(value)))
                setattr(self, key, value)
        return value

If the first two magic methods are not defined, the next two class methods will not work

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template