Created
May 19, 2020 16:58
-
-
Save ZhouYang1993/1287bffc4863f31d3474f9b24f2e8f92 to your computer and use it in GitHub Desktop.
Class Method and Static Method in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Student: | |
| def __init__(self, first_name, last_name): | |
| self.first_name = first_name | |
| self.last_name = last_name | |
| @classmethod | |
| def get_from_string(cls, name_string: str): | |
| first_name, last_name = name_string.split() | |
| return Student(first_name, last_name) | |
| @staticmethod | |
| def static_get_from_string(name_string): | |
| first_name, last_name = name_string.split() | |
| return Student(first_name, last_name) | |
| class NewStudent(Student): | |
| age = 6 | |
| new_s1 = NewStudent.get_from_string('yang zhou') | |
| new_s2 = NewStudent.static_get_from_string('yang zhou') | |
| print(isinstance(new_s1, NewStudent)) # False | |
| print(isinstance(new_s2, NewStudent)) # False | |
| print(isinstance(new_s1, Student)) # True | |
| print(isinstance(new_s2, Student)) # True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment