"""
callable(对象)
对象() 能不能运行就是callable判断的事
__call__ 对象() 调用这个类中的__call__方法
"""
class A:
def __call__(self, *args, **kwargs):
print("*************")
obj = A()
print(callable(obj))
obj()
#Flask框架的源码
"""
__len__
"""
class Cls:
def __init__(self,name):
self.name = name
self.students = []
def __len__(self):
return len(self.students)
py = Cls("python")
py.students.append("xx")
py.students.append("zz")
py.students.append("cc")
print(len(py))
"""
__new__
"""
class A:
def __new__(cls, *args, **kwargs): # 构造方法
n = super().__new__(cls)
print("执行了new", n)
return n
def __init__(self):
print("执行init", self)
A()
# 实例化的时候
# 先创建一块对象空间,有一个指针能指向类 ————》 __new__
# 调用init
# 设计模式 -- 单例模式
# 一个类从头到尾只会创建一次self的空间
class Baby:
__instance = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = super().__new__(cls)
return cls.__instance
def __init__(self, close, pants):
self.close = close
self.pants = pants
b1 = Baby("红衣", "白裤")
b2 = Baby("黑衣", "蓝裤")
print(b1.close)
print(b2.close)
# 单例模式,从模块导入更简单,模块导入只会导入一次
"""
__str__
__repr__
"""
class Course:
def __init__(self, name, price, period):
self.name = name
self.price = price
self.period = period
def __str__(self):
return ",".join([self.name, str(self.price), self.period])
python = Course("python", 1999, "6个月")
java = Course("java", 1999, "6个月")
mysql = Course("mysql", 1999, "6个月")
linux = Course("linux", 1999, "6个月")
lst = [python, java, mysql, linux]
for c in lst:
print(c)
# 当我们打印一个对象 用%s进行字符串拼接 或者str(对象)总是调用这个对象的__str__方法
# 如果找不到__str__,就调用repr方法
# __repr__不仅是__str__的替代品,还有自己的功能
# 用%r进行字符串拼接 或者用repr(对象)的时候总是调用这个对象的__repr__方法