1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
""" 触发时机:实例化类生成对象的时候触发(触发时机在__init__之前) 功能:控制对象的创建过程 参数:至少一个cls接受当前的类,其他根据情况决定 返回值:通常返回对象或者None
"""
class Myclass2(): a = 100
obj2 = Myclass2() class MyClass1(): def __new__(cls): return object.__new__(cls)
obj = MyClass1() print(obj)
""" 先有对象,才能初始化对象 __new__ 创建对象 __init__ 初始化对象 """
class Myclass(): def __init__(self): print(2)
def __new__(cls): print(1) return object.__new__(cls)
obj = Myclass()
class Boat(): def __new__(cls, name): return object.__new__(cls) def __init__(self,name): self.name = name
obj = Boat("山东舰") print(obj.name)
class Boat(): def __new__(cls, *args, **kwargs): return object.__new__(cls) def __init__(self,name,type): self.name = name self.type = type
obj = Boat("山东舰","304不锈钢") print(obj.name,obj.type)
""" 如果__new__没有返回对象或者返回的是其他类的对象,不会调用构造方法 只有在返回自己本类对象的时候,才会调用构造方法 """ class Children(): def __new__(cls, *args, **kwargs): return object.__new__(cls) def __init__(self,name,skin): self.name = name self.skin - skin
|