python __new__ __init__

class Student():
    def __new__(cls, *args, **kwargs):##创建类的实例
        print('__new__')
        return object.__new__(cls)##此处返回才会调用__init__
    def __init__(self):##初始化类的实例
        print('__init__')

class NewInt(int):
    def __new__(cls, value):
        return int.__new__(cls,abs(value))
#单例横式
class Person():
    __isinstance=False
    def __new__(cls, *args, **kwargs):
        if cls.__isinstance:
            return cls.__isinstance
        else:
            cls.__isinstance = object.__new__(cls)
            return cls.__isinstance
    def __init__(self):
        print('3333')
if __name__=='__main__':
  stu=Student()
  nint=NewInt(-2.45)
  print(nint) ##2
  p1=Person()
  p2 = Person()
  print(p1,p2)

  

posted @ 2023-12-07 11:34  howhy  阅读(1)  评论(0编辑  收藏  举报