class singleton pattern

# new: automatically called when creating an object
# new principle: return value, return value object, current class -- condition meets init
# instance object -- instance
class Person(object):
    cls_shuxing = None
    # Control the switch that does only one initialization -- the switch is turned on -- it means judgment
    is_First = True
    def __new__(cls, *args, **kwargs):
        if cls.cls_shuxing == None:
            # create object -- new
            cls.cls_shuxing = super () .__ new __ (cls)
        return cls.cls_shuxing


    def __init__(self, name,age, sex,id):
        if self.is_First == True: # The implementation does only one initialization
            self.name = name
            self.age = age
            self.sex = sex
            self.id = id
            # turn off the switch
            self.is_First = False

    def __str__(self):
        return 'name is %s, age is %s, gender is %s, id is %s' % (self.name, self.age, self.sex, self.id)

dafan = Person('Dafan', 18, 'Female',id=100)
print (dafan)
erfan = Person('Erfan', 20, 'Male', id=110)
print (erfan)

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325873269&siteId=291194637