避免分配给未定义的类属性的最佳设计决策
考虑以下代码:
class Test:
def __init__(self):
self.historical = 5
t = Test()
# correct
print(t.historical)
# ops .. I made a mistake!
# an attribute error is thrown
#print(t.history)
# let's redefine the variable
# correct!
t.historical = 10
# ops ... I made a mistake!
t.history = 15 # <-- I want Python to throw an exception here
print(t.historical)
print(t.history)
在这段代码中,我犯了一个错误:我分配给 history
,而正确的属性名称是 historical
。
当我分配给 history
时,如何让 Python 抛出异常?
实现这一目标的最佳设计决策是什么?
Consider the following code:
class Test:
def __init__(self):
self.historical = 5
t = Test()
# correct
print(t.historical)
# ops .. I made a mistake!
# an attribute error is thrown
#print(t.history)
# let's redefine the variable
# correct!
t.historical = 10
# ops ... I made a mistake!
t.history = 15 # <-- I want Python to throw an exception here
print(t.historical)
print(t.history)
In this code, I made a mistake: I assigned to history
while the correct attribute name was historical
.
How can I have Python throw an exception when I assign to history
?
What is the best design decision to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论