【发布时间】:2022-11-22 23:30:18
【问题描述】:
我正在尝试创建一个 Customer 类,它从 sqlalchemy 查询对象创建它的属性。
data = {'Name':'John Doe','Age':67}
class Customer:
def __init__(self,data) -> None:
assert type(data) == Customers
for key in data.keys():
exec(f"self.__{key[1:] if key.startswith('_') else key} = data['{key}']",{'self':self,'data':data})
@property
def name(self):
return self.__Name
data['bank'] = green
person = Customer(data)
我能够将客户属性作为公共属性访问:
print(person.__Name)
它打印出John Doe
但是当我尝试通过名称方法访问属性时,
像这样 :
print(person.name)
它引发了一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\HP\PyProject\FlaskProject\green\bank\modelx.py", line 66, in name
return self.__Name
AttributeError: 'Customer' object has no attribute '_Customer__Name'
如何使在 exec 函数中创建的类属性充当类的私有属性而不是公共属性。
【问题讨论】:
-
通过
exec设置时,名称修改不起作用,它是在编译时完成的,因此self.__...必须确实存在于源代码中,而不是在运行时拼凑在一起。
标签: python python-3.x