一、python中类的特殊成员
1.__init__ 初始化方法
2.__new__ 构造方法
通过 类() 会执行 __new__ 和 __init__ 方法
3.__call__
通过 对象() 会执行 __call__ 方法
4.__str__
里面必须返回一个字符串
data = str(obj)会执行对象里的__str__方法 data为方法里返回的字符串
如果有 __str__ 方法,直接输出也会执行 __str__ 方法
5.__dict__
print(obj.__dict__) 将实例变量转换成字典输出
6.__getitem__ __setitem__ __delitem__
使用像字典一样
7.__enter__ __exit__
上下文管理语法: with obj as f: 也可以不写对象,直接写 类()
with + 对象 会自动执行 __enter__方法, __enter__里面可以有返回值,返回值是什么,f就是什么
当with缩进的代码执行完毕后,会自动执行 __exit__ 方法
8.__add__ 两个对象相加(还有加减乘除平方等)
二、使用案例
class Foo(object):
def __init__(self, name):
self.name = name
obj1 = Foo("小虾米")
class Foo(object):
def __init__(self, name):
print("第二步:初始化对象,在空对象中创建数据")
self.name = name
def __new__(cls, *args, **kwargs):
print("第一步:先创建空对象并返回")
return object.__new__(cls)
obj2 = Foo("小虾米")
class Foo(object):
def __call__(self, *args, **kwargs):
print("执行call方法")
obj = Foo()
obj()
class Foo(object):
def __str__(self):
return "HHHHHH"
obj = Foo()
data = str(obj)
print(data)
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "{}-{}".format(self.name, self.age)
s1 = Student("aa", 19)
s2 = Student("bb", 20)
s3 = Student("cc", 21)
print(s1)
class Foo(object):
def __init__(self, name, age):
self.name = name
self.age = age
obj = Foo("小虾米", 21)
print(obj.__dict__)
class Foo(object):
def __setitem__(self, key, value):
print(key, value)
def __getitem__(self, item):
print(item)
def __delitem__(self, key):
print(key)
obj = Foo()
obj["x1"] = 123
obj["000"]
del obj["000"]