-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass_methods.py
More file actions
44 lines (31 loc) · 1.12 KB
/
class_methods.py
File metadata and controls
44 lines (31 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Class methods = allow operations related to the class
# takes class (cls) as the first parameter
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
@classmethod
def get_student_count(cls):
print(f"Total students: {cls.count}")
@classmethod
def get_average_gpa(cls):
print(f"Average GPA: {cls.total_gpa / cls.count:.2f}")
bob = Student("Bob", 4.5)
sam = Student("Sam", 2.5)
mike = Student("Mike", 1.4)
Student.get_student_count()
Student.get_average_gpa()
bob.get_student_count() # Instance can access the class method
# EXTRA: HOW TO MAKE A METHOD INACCESSIBLE TO INSTANCES
class MyClass:
def class_only(cls):
if not isinstance(cls, type):
raise TypeError("Use the method on the class, cannot be called by an instance")
print("Class-only method")
my_instance = MyClass()
MyClass.class_only(MyClass) # Output: Class-only method
my_instance.class_only() # TypeError: Use the method on the class, cannot be called by an instance