https://docs.python.org/2/library/functions.html?highlight=getattr#getattr
-
getattr
(
object,
name
[,
default
]
)
-
Return the value of the named attribute of object. name must be a string.If the string is the name of one of the object’s attributes, the result is thevalue of that attribute. For example,getattr(x,'foobar') is equivalent tox.foobar. If the named attribute does not exist,default is returned ifprovided, otherwiseAttributeError is raised.
=============================================================================================
def __init__(self, name=None, **kwargs):
if name is not None:
self.name = name
elif not getattr(self, 'name', None):
raise ValueError("%s must have a name" % type(self).__name__)
self.__dict__.update(kwargs)
if not hasattr(self, 'start_urls'):
self.start_urls = []
if not getattr(str, '__invalid__', 'string'):
print 'No' # 不打印No
if not getattr(str, '__invalid__', None):
print 'No' # 打印No
x = not getattr(str, 'string', None) # x = True
y = not getattr(str, 'string', 'string') # y = False
=============================================================================================
-
hasattr
(
object,
name
)
-
The arguments are an object and a string. The result is True if the stringis the name of one of the object’s attributes, False if not. (This isimplemented by calling getattr(object, name) and seeing whether it raises anexception or not.)