Why does this work:
class A:
class BError(Exception):
pass
class CError(AError):
pass
But this doesn't:
class A:
class BError(Exception):
pass
class CError(A.BError):
pass
If "method 1" works for calling class variables, why doesn't it work for "class classes"
When compiling, python builds the class and then assigns it to a named variable in the enclosing namespace. In the first example (assuming you really meant class CError(BError)
), BError
has been compiled and assigned to the A
class namespace so it is visible for the next class. But in the second example, the top class has not yet been assigned to the global A
variable so A.BError
cannot be found.
The problem can be demonstrated as:
>>> class A:
... print('A' in globals())
...
False
>>> print('A' in globals())
True
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.