The timing of the error will change depending on the type annotation.
Defines classes that do not initialize by declaring variables.Test 2 only provides type annotations.
class Test1:
def__init__(self):
self.a = 1
self.b
Class Test 2:
def__init__(self):
self.a = 1
self.b:int
>>>test1=Test1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
AttributeError: 'Test1' object has no attribute'b'
I understand this, but
>>>test2=Test2()
>> test 2.b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Test2' object has no attribute'b'
It is strange that the error does not appear until you refer to test2.b
.
>>vars(test2)
{'a':1}
I understand that test2.b
does not exist, but I wonder why the error does not appear when instantiated.
This is because it is impossible to say "only type annotation" if an error occurs in the line of type annotation only.
(Additional)
It was listed in PEP526.
https://www.python.org/dev/peps/pep-0526/ #global-and-local-variable-announotations
Being able to commit the initial value allowances for easy typing of variables assigned in conditional branches:
ane_world:bool
if 2 + 2 == 4:
sane_world=True
else:
sane_world=False
Omitting the initial value leaves the variable initialized:
a:int
print(a)#raiseNameError
© 2024 OneMinuteCode. All rights reserved.