def add_age(cls,age):
cls.yrs_old = age
return cls
class Test:
age = add_age
a = Test()
a.age(5)
print(a.yrs_old)
So I was toying around with python and this is something I've never encountered before
here I defined a global function called add_age
assigned add_age
to the age
attribute of Test
what surprises me is that add_age
takes 2 arguments cls
and age
so I tried this
a = Test
a.age(a,5)
print(a.yrs_old)
works as expected however doing this:
a = Test()
a.age(a,5)
print(a.yrs_old)
throws an error TypeError: add_age() takes 2 positional arguments but 3 were given
so then I said well let's try taking out one argument so I did this:
a = Test()
a.age(5)
print(a.yrs_old)
The class itself is automatically passed as the first argument.almost like self
and the age
attribute now acts as regular class method
which to me as a python newbie is mind boggling
can someone give some insight on what is happening?