Created
June 5, 2020 04:49
-
-
Save ZhouYang1993/9fa80503e22e2246825f0cf6de99a480 to your computer and use it in GitHub Desktop.
Understand Constructors in Python Classes
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 Singleton_Student(object): | |
| _instance = None | |
| def __new__(cls, *args, **kwargs): | |
| print("Running __new__() method.") | |
| if not Singleton_Student._instance: | |
| Singleton_Student._instance = object.__new__(cls) | |
| return Singleton_Student._instance | |
| def __init__(self, first_name, last_name): | |
| print("Running __init__() method.") | |
| self.first_name = first_name | |
| self.last_name = last_name | |
| s1 = Singleton_Student("Yang", "Zhou") | |
| s2 = Singleton_Student("Elon", "Musk") | |
| print(s1) | |
| print(s2) | |
| print(s1 == s2) | |
| print(s1.last_name) | |
| print(s2.last_name) | |
| # Running __new__() method. | |
| # Running __init__() method. | |
| # Running __new__() method. | |
| # Running __init__() method. | |
| # <__main__.Singleton_Student object at 0x7ff1e5a53198> | |
| # <__main__.Singleton_Student object at 0x7ff1e5a53198> | |
| # True | |
| # Musk | |
| # Musk |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment