相关疑难解决方法(0)

在为班级成员设定价值时如何保护错字?

请考虑以下示例:

class A():
    def __init__(self):
        self.veryImportantSession = 1

a = A()
a.veryImportantSession = None # ok

# 200 lines below
a.veryImportantSessssionnnn = 2 # I wanna exception here!! It is typo!
Run Code Online (Sandbox Code Playgroud)

如果我尝试设置未设置的成员,我怎么能这样做才会引发异常__init__

上面的代码在执行时不会失败,但是给我一个有趣的时间来调试问题.

跟str一样:

>>> s = "lol"
>>> s.a = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'a'
Run Code Online (Sandbox Code Playgroud)

谢谢!

python

5
推荐指数
1
解决办法
447
查看次数

标签 统计

python ×1