Learn Python CLASS METHODS in 6 minutes! π«
# Class methods = Allow operations related to the class itself # Take (cls) as the first parameter, which represents the class ...

Bro Code
90.2K views β’ Jul 5, 2024

About this video
# Class methods = Allow operations related to the class itself
# Take (cls) as the first parameter, which represents the class itself.
# Instance methods = Best for operations on instances of the class (objects)
# Static methods = Best for utility functions that do not need access to class data
# Class methods = Best for class-level data or require access to the class itself
class Student:
count = 0
total_gpa = 0
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
Student.count += 1
Student.total_gpa += gpa
#INSTANCE METHOD
def get_info(self):
return f"{self.name} {self.gpa}"
@classmethod
def get_count(cls):
return f"Total # of students: {cls.count}"
@classmethod
def get_average_gpa(cls):
if cls.count == 0:
return 0
else:
return f"Average gpa: {cls.total_gpa / cls.count:.2f}"
student1 = Student("Spongebob", 3.2)
student2 = Student("Patrick", 2.0)
student3 = Student("Sandy", 4.0)
print(Student.get_count())
print(Student.get_average_gpa())
# Take (cls) as the first parameter, which represents the class itself.
# Instance methods = Best for operations on instances of the class (objects)
# Static methods = Best for utility functions that do not need access to class data
# Class methods = Best for class-level data or require access to the class itself
class Student:
count = 0
total_gpa = 0
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
Student.count += 1
Student.total_gpa += gpa
#INSTANCE METHOD
def get_info(self):
return f"{self.name} {self.gpa}"
@classmethod
def get_count(cls):
return f"Total # of students: {cls.count}"
@classmethod
def get_average_gpa(cls):
if cls.count == 0:
return 0
else:
return f"Average gpa: {cls.total_gpa / cls.count:.2f}"
student1 = Student("Spongebob", 3.2)
student2 = Student("Patrick", 2.0)
student3 = Student("Sandy", 4.0)
print(Student.get_count())
print(Student.get_average_gpa())
Tags and Topics
Browse our collection to discover more content in these categories.
Video Information
Views
90.2K
Likes
2.1K
Duration
6:46
Published
Jul 5, 2024
User Reviews
4.7
(18) Related Trending Topics
LIVE TRENDSRelated trending topics. Click any trend to explore more videos.
No specific trending topics match this video yet.
Explore All Trends