I'm trying to learn about the basic construction of the python class. I have the following code which is completely running fine:
class Test1:
name = 'Choton'
age = 28
class Test2: # __init__ function executes whenever the class is called
def __init__(self):
self.name = 'Choton'
self.age = 28
print('Class Test2 is called and initialized...')
def main():
# Test1
print(f'Test1:')
print(f'Test1().name = {Test1().name}, Test1().age = {Test1().age}')
print(f'Test1.name = {Test1.name}, Test1.age = {Test1.age}\n')
# Test2
print(f'Test2:')
print(f'Test2().name = {Test2().name}, Test2().age = {Test2().age}')
# DOES NOT WORK
# print(f' name = {Test2.name}, age = {Test2.age}')
if __name__ == '__main__':
main()
I know that the __init__ function always runs whenever a class is initialized. Here the Test1 class do not have any __init__ function and both Test1.name and Test1().name works fine. But whenever I am calling the name using the __init__ function in Test2, the Test2.name does not work anymore. It says the following error if I uncomment that line: AttributeError: type object 'Test2' has no attribute 'name'.
What is the difference in here? Why both syntax work for one class and not for the other? I am a bit confused about it. Is there any syntactic sugar in here or any generalization that I am missing?
Test1has class attributes, which can be accessed either via the class (Test1.x) or an instance of the class (Test1().x).Test2has only instance attributes, they are not accessible via the class itself.Test1'snameandageare class attributes andTest2's are instance attributes. Printvars(Test1)andvars(Test2)and you will find thatTest1contains'name'and'age'whileTest2does not.Test1.xand 'Test1().x` ? Shouldn't onlyTest1.xbe working andTest1().xbe an error as it is an instance? This seems confusing to me.