Topics:
1. Class Methods
2. Class Method vs Static Method
1. Class Method
>>Return to Menu
class PlayerCharacter:
position = "defender"
def __init__(self,name="Sally",age=50):
self.name = name
self.age = age
def greet(self):
return f'Hello, {self.name}!'
@classmethod
def person(cls,call_name,call_age):
return cls(f'My name is {call_name}.', f'I am {call_age} years old.')
player1 = PlayerCharacter('Bob',23)
player2 = PlayerCharacter('Mary',30)
print(player1.name)
print(player2.age)
print(player1.greet())
player3 = PlayerCharacter.person('Tom',15)
print(player3.name)
print(player3.age)
2. Class Method vs Static Method
>>Return to Menu
- Class method takes (cls) as first parameter, while static method need no specific parameters.
- Static methods know nothing about the class state, while class methods can access and modify class state.
- Classmethod decorators are used to create class methods, Staticmethod decorators are used to create static methods.
class Student:
def __init__(self,name,marks):
self.name = name
self.marks = marks
def report(self):
return f"{self.name} got {self.marks}%."
@classmethod
def get_percentage(cls,name,marks):
return cls(name.upper(),"{:.2f}".format((marks/600)*100))
@staticmethod
def get_age(age):
return "Too young for College." if age<17 else "Ready for College."
student1 = Student("Mike",520)
print(student1.get_age(16))
print(student1.get_age(20))
student2 = Student.get_percentage("Mike",520)
print(student2.report())
#End
Hope you enjoyed this! :) Follow me for more contents...
Get in Touch:
ifeanyiomeata.com
contact@ifeanyiomeata.com
Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2022