Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
Last active December 20, 2022 17:59
Show Gist options
  • Save ZhouYang1993/c5606e64c813ea6a190b0069cf3a931a to your computer and use it in GitHub Desktop.
Save ZhouYang1993/c5606e64c813ea6a190b0069cf3a931a to your computer and use it in GitHub Desktop.
Class Method and Static Method in Python
class Student:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.nickname = None
def set_nickname(self, name):
self.nickname = name
@classmethod # get_from_string is a class method
def get_from_string(cls, name_string: str):
first_name, last_name = name_string.split()
return Student(first_name, last_name)
s = Student.get_from_string('yang zhou')
print(s.first_name) # yang
print(s.last_name) # zhou
# can't call instance method directly by class name
s2 = Student.set_nickname('yang')
# TypeError: set_nickname() missing 1 required positional argument: 'name'
@alex-96-eng
Copy link

alex-96-eng commented Dec 20, 2022

line13: you should just inject the attributes directly into the constructor with cls:

class Student:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.nickname = None

    def set_nickname(self, name):
        self.nickname = name

    @classmethod
    def from_string(cls, name_string: str):
        first_name, last_name = name_string.split()
        return cls(first_name, last_name)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment