近日在学习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
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:
Note: The above code is similar to pseudo code and cannot be run directly. It is only used for auxiliary explanation.
If the first two magic methods are not defined, the next two class methods will not work