Super and Singleton

What "super" does it to avoid tedious redefining the attributes (you did in the "Parent" class).


#------------Save as "precar.py" ---------------
class Person():

    def __init__(self, name, birth):
        self._name = name
        self._birth = birth

    def details(self):
        return 'Name = {} , Birth = {}'.format(self._name ,self._birth)

    def getname(self):
        return self._name

    def getbirth(self):
        return self._birth


class Onlyone:
    _singleton = None
    def __new__(cls, *args, **kwargs):
        if not cls._singleton:
            cls._singleton = super().__new__(cls,*args,**kwargs)
        return  cls._singleton

#----------------------- end   -------------------------

#-------------------save as "run.py"--------------------
from precar import *

class Student(Person):

    def __init__(self, name, birth, id, major):
        self._id = id
        self._major = major
        # if not super() here, the program will
        # find the _name and _birth attributes !
        super().__init__(name, birth)

    def getid(self):
        return self._id

    def details(self):
        return super().details() + '  and Major is {}'.format(self._major )

mystu = Student('Jarimi', 2001, 'M7451235', 'Art')
print(mystu.getbirth())
print(mystu.getid())
print(mystu.details())


##################
print()
print(' ------Singleton------- ')
g = Onlyone()
h = Onlyone()
print('g is h : {}'.format(g is h))
print('g == h : {}'.format(g == h))
#--------------------- end ---------------------------


#Output:
#-----------------------------------------------------
2001
M7451235
Name = Jarimi , Birth = 2001  and Major is Art

 ------Singleton-------
g is h : True
g == h : True
#------------------------------------------------------

留言

這個網誌中的熱門文章

AndrewNg's CNN notes(practical issues)

Confidence intervals & Credible intervals