一、基本用法
# 从一个类建立一个对象
# __new__ 从class建立一个object过程
# __init__ 有了object初始化过程
class Language:
def __new__(cls, *args, **kwargs):
print("__new__")
return super().__new__(cls)
def __init__(self):
print("__init__")
language = Language()
-------------------------
__new__
__init__
二、类似负载分担的作用
可以在实例化时根据输入参数选择对应的类
class Sex:
def __new__(cls, *args, **kwargs):
if kwargs.get('sex') == 'man':
return Man()
elif kwargs.get('sex') == 'woman':
return Woman()
else:
return super(Sex, cls).__new__(cls)
def say(self):
print("我看你不是人!")
class Man:
def say(self):
print("this is a man")
class Woman:
def say(self):
print("this is a woman")
sex = Sex(sex="man")
sex.say()
sex = Sex(sex="woman")
sex.say()
sex = Sex(sex="waixingren")
sex.say()
---------------------------
this is a man
this is a woman
我看你不是人!
标签:__,python,sex,say,print,new,def
From: https://www.cnblogs.com/twitedfate/p/17547707.html