python-魔法函数,new, init, call
new: 构造函数,创建实例对象,返回实例对象
init: 初始化实例对象
顺序:先__new__ 再 init
call: 对象可被调用
# -*- coding: utf-8 -*-
class Apple(object):
def __init__(self):
"""
用于对象属性的初始化
"""
self.name = "apple"
print("This is an apple")
def __call__(self, *args, **kwargs):
return self.name
class Pear(object):
def __init__(self):
"""
用于对象属性的初始化
"""
self.name = "pear"
print("This is a pear")
def __call__(self, *args, **kwargs):
return self.name
class Fruit(object):
def __new__(cls, *args, **kwargs):
"""
构造函数, 创建实例对象, 返回一个对象
:param args:
:param kwargs:
"""
name = kwargs["name"]
return globals()[name.title()]()
if __name__ == '__main__':
f = Fruit(name="apple")
print(f.__class__)
print(f())
f = Fruit(name="pear")
print(f.__class__)
print(f())