
They behave like plain functions except that you can call them from an instance or the class: a.static_foo(1) With staticmethods neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. One use people have found for class methods is to create inheritable alternative constructors. A.foo(1) would have raised a TypeError, but A.class_foo(1) works just fine: A.class_foo(1) In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. You can also call class_foo using the class. With classmethods The class of the object instance is implicitly passed as the first argument instead of self. The object instance, a, is implicitly passed as the first argument. Print "executing class_foo(%s, %s)" % (cls, static_foo(x):īelow is the usual way an object instance calls a method. Print "executing foo(%s, %s)" % (self, class_foo(cls, x):
#Animal age in human years code#
Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo: class A(object): Next: Write a Python program to check whether an alphabet is a vowel or consonant.ĭifference between staticmethod and classmethod: Previous: Write a Python program to print alphabet pattern 'Z'. Have another way to solve this solution? Contribute your code (and comments) through Disqus. The following tool visualize what the computer is doing step-by-step as it executes the said program: Sample Output: Input a dog's age in human years: 12 Print("The dog's age in dog's years is", d_age) Python Code: h_age = int(input("Input a dog's age in human years: ")) After that, each dog year equals 4 human years. Note: For the first two years, a dog year is equal to 10.5 human years. Write a Python program to calculate a dog's age in dog's years.


Python Conditional: Exercise - 31 with Solution
