classPeople:# 初始化方法def__init__(self, name):
self.__name = name
self.parts =["head","leg","body"]# f'content' 格式化字符串def__format__(self, format_spec):return self.__name
# 字符串方法def__repr__(self):# 如果没有此方法则会打印 <People 内存地址>return f"People(name={self.__name})"def__str__(self):# 字符串表示return self.__name
# 上下文管理器的开始与退出方法def__enter__(self):print(f"{self.__name} is Waking up !")def__exit__(self, exc_type, exc_val, exc_tb):print(f"{self.__name} is going to sleep...")# 获取长度def__len__(self):returnlen(self.parts)# 列表方法def__setitem__(self, index, value):
self.parts[index]= value
def__getitem__(self, item):return self.parts[item]# 使用 . 对属性进行赋值以及取值
@propertydefage(self):return self.__age
@age.setter
defage(self, value):
self.__age = value
# 实例方法deflearn(self):print(f"{self.__name} is Learning")
执行结果:
>>> people = People("Jack")>>>print(f"my name is {people}")>>> my name is Jack
>>>print(repr(people))>>> People(name=Jack)>>>with People("Jack")as p:>>>print("I am Working!")>>> Jack is Waking up !
>>> I am Working!
>>> Jack is going to sleep...>>>for p in people:>>>print(p, end=", ")>>> head, leg, body,>>>print("\n Handstand!")>>> Handstand!
>>>for p inreversed(people):print(p, end=", ")>>> body, leg, head,>>> people.age ="12">>>print(people.age)>>>12