Python, ClassMethods | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Python, ClassMethods

class Person: age=25 @classmethod def printAge(cls): print('The age is:',cls.age) #remember cls parameter relates to class P=Person.printAge() print(P). Why the output shows None?. Thanks in Advance.

1st Sep 2019, 6:57 AM
Harshit Garg
5 Answers
+ 2
By default, a function that has no return statment returns None. Here, in printAge, it is the case, that's why P is None.
1st Sep 2019, 8:23 AM
Théophile
Théophile - avatar
+ 1
If I understood correctly, it should be like this: P = Person P.printAge() printAge() - class method "P".
1st Sep 2019, 8:21 AM
Solo
Solo - avatar
+ 1
you can do print(p) if u implement a __str__() or __repr() method.
1st Sep 2019, 8:48 AM
rodwynnejones
rodwynnejones - avatar
+ 1
class Person: age = 25 @classmethod def printAge(cls): return(cls.age) P = Person.printAge() print('The age is:',P)
1st Sep 2019, 10:35 AM
Solo
Solo - avatar
0
Cbr✔[ Exams ] In your example, one line is enough: P = Person.printAge () - It simultaneously assigns and calls the classmetod. And separately "P" cannot call the classmetod.
2nd Sep 2019, 8:36 AM
Solo
Solo - avatar