#类的特殊成员
class Foo():
def __init__(self,name,age):
self.age = age
self.name = name
def __int__(self):
return 23
#对象的返回值
#print(obj)就会自动执行对象的__str__方法
#也就是说执行print对象,就会自动执行对象的__str__方法,并打印该方法的返回值
def __str__(self):
return f'{self.name}-{self.age}'
def __del__(self):
print('析构方法,在对象销毁的时候自动执行')
obj = Foo('bob',23)
# #想要将对象进行类型转换
# r = int(obj)
# print(r)
#
#
# res = str(obj)#执行此语句就会执行obj对象的特殊方法__str__
# print(res)
print(obj)
#对两个对象进行相加
class Foos():
def __init__(self,name,age):
self.name = name
self.age = age
def __add__(self, other):
#return 'xxx00'
#self--->obj1
#other--->obj2
#return self.age + other.age
return Foos(obj1.name,other.age)
def __str__(self):
return f'{self.name}-{self.age}'
obj1 = Foos('alex',19)
obj2 = Foos('mary',23)
#要求两个对象相加的结果,就会自动执行第一个对象内的__add__方法
#并把第二个对象作为参数传入使用
print(obj1+obj2)
#__dict__:该方法作用是将对象中封装的所有内容以字典的形式返回
class S():
'''__dict__作用'''
def __init__(self,name,age):
self.name = name
self.age = age
self.hobby = 'play'
obj3 = S('alex',34)
print(obj3.__dict__)
print(S.__doc__)
#__getitem__ __setitem__ __delitem__ 方法
class Haa():
def __init__(self, name, age):
self.name = name
self.age = age
#获取必须有返回值
def __getitem__(self, item):
return item +10
#设置不需要返回值
def __setitem__(self, key, value):
print(key,value)
def __delitem__(self, key):
print(key)
obj4 = Haa('john',34)
result = obj4[8]#对这个对象obj4进行索引,就会执行这个对象的类中的__getitem__方法,
# 并把索引传给item
print(result)
obj4[3] = 100
del obj4[5]