If you add a type annotation, you can instantiate it even if you can't initialize it with _init__.

Asked 2 years ago, Updated 2 years ago, 31 views

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.

python python3

2022-09-30 16:16

1 Answers

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


2022-09-30 16:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.