class ValidatingDB(object):
def __init__(self):
self.exists = 5
def __getattribute__(self, name):
print('Called __getattribute__(%s)' % name)
try:
return super(ValidatingDB, self).__getattribute__(name)
except AttributeError:
value = 'Value for %s' % name
setattr(self, name, value)
return value
data = ValidatingDB()
data.exists
data.foo
data.foo
我希望第一次调用data.foo会“设置”,第二次调用data.foo将不再产生AttributeError。为什么它会为每次调用data.foo?
引发AttributeError答案 0 :(得分:0)
您的代码不允许您查看<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE message SYSTEM "work_request_20.dtd">
<message message_id="1005" message_dt="01/21/2008 09:50:23.221 AM" message_type="Work_Request" message_sub_type="New" message_dtd_version_number="2.0">
<header>
<from_application_id>3367e115-c873-4ac9-a1dd-7e45231dc3d5</from_application_id>
<to_application_id>35e0cca2-e423-4ffe-ba07-7d056775c228</to_application_id>
</header>
<body>
<work_request requisition_number="REQ44">
<client client_id="44">
<first_name>Barak</first_name>
<last_name>Obama</last_name>
</client>
<patient patient_id="4444" patient_species="CANINE" patient_gender="MALE_INTACT">
<patient_name>Bo</patient_name>
<patient_breed>Portuguese Water Dog</patient_breed>
<patient_birth_dt>04/04/2004</patient_birth_dt>
<patient_weight patient_weight_uom="lbs">
<weight>44.4</weight>
</patient_weight>
</patient>
<doctor>
<first_name>Surgeon</first_name>
<last_name>General</last_name>
</doctor>
<service_add>
<service_cd>ALB</service_cd>
<service_cd>GLU</service_cd>
<service_cd>BUN</service_cd>
</service_add>
</work_request>
</body>
</message>
与现有属性之间的区别。在这两种情况下,您都会得到完全相同的结果。
因此,第一个AttributeError
访问权限会引发data.foo
,因此会创建一个新值,设置并返回。
第二个AttributeError
访问权限返回您已设置的值。这与之前的表达式无法区分,因为在这两种情况下都会得到一个值。
当引发data.foo
时,您必须更改代码执行某些操作 else 。您可以添加额外的AttributeError
语句,例如:
print
现在你会发现不同之处:
def __getattribute__(self, name):
print('Called __getattribute__(%s)' % name)
try:
return super(ValidatingDB, self).__getattribute__(name)
except AttributeError:
print('No such attribute, generating a new value')
value = 'Value for %s' % name
setattr(self, name, value)
return value