Skip to main content

Command Palette

Search for a command to run...

#16 - Class Methods

By Ifeanyi Omeata

Updated
2 min read
#16 - Class Methods
I

Hi, I am a Software Developer of 3-4 years specialising in React, Javascript, Node, NextJS, Express, Python, Django, Fast API, SQL and a few other technology stack, with a good background in Networking and Cloud Infrastructure. I am working to become a DevOps Solutions Engineer and happily married to my long time girlfriend.


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)

image.png


2. Class Method vs Static Method


>>Return to Menu

  1. Class method takes (cls) as first parameter, while static method need no specific parameters.
  2. Static methods know nothing about the class state, while class methods can access and modify class state.
  3. 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())

image.png

#End


Hope you enjoyed this! :) Follow me for more contents...


Get in Touch:
www.ifeanyiomeata.com
contact@ifeanyiomeata.com
Youtube: https://www.youtube.com/c/IfeanyiOmeata
Linkedin: https://www.linkedin.com/in/omeatai/
Twitter: https://twitter.com/iomeata
Github: https://github.com/omeatai/
Stackoverflow: https://stackoverflow.com/users/2689166/omeatai
Hashnode: https://hashnode.com/@omeatai
Medium: https://medium.com/@omeatai
© 2022

LEARN PYTHON/DJANGO

Part 21 of 37

Learn Python and Django the easy way!..... PYTHON | DJANGO | FASTAPI

Up next

#15 - Python Classes and Objects

By Ifeanyi Omeata