1. python 类对象可进行格式化和转换,输出对应的内置object方法,以及与运算符重载
class MyClass: # 自定义一个类
def __init__(self, name, age): # 定义该类的初始化函数
self.name = name # 将传入的参数值赋值给成员交量
self.age = age
def __str__(self): # 用于将值转化为字符串形式,等同于 str(obj)
return "name:" + self.name + ";age:" + str(self.age)
__repr__ = __str__ # 转化为供解释器读取的形式
def __lt__(self, record): # 重载 self < record 运算符
if self.age < record.age:
return True
else:
return False
def __add__(self, record): # 重载 + 号运算符
return MyClass(self.name, self.age + record.age)
myc = MyClass("Anna", 42) # 实例化一个对象 Anna,并为其初始化
mycl = MyClass("Gary", 23) # 实例化一个对象 Gary,并为其初始化
print(repr(myc)) # 格式化对象 myc,
print(myc) # 解释器读取对象 myc,调用 repr
print(str(myc)) # 格式化对象 myc ,输出"name:Anna;age:42"
print(myc < mycl) # 比较 myc<mycl 的结果,输出 False
print(myc + mycl) # 进行两个 MyClass 对象的相加运算,输出 "name:Anna;age:65"
2. __new__是在创建实例的时候调用,__init__是在初始化时候调用;__new__在前,__init__在后,__new__是类级别的,__init__是对象级别的;__new__必须有返回值;
class demoClass:
instances_created = 0
def __new__(cls, *args, **kwargs):
print("__new__():", cls, args, kwargs)
instance = super().__new__(cls)
instance.number = cls.instances_created
cls.instances_created += 1
return instance
def __init__(self, attribute):
print("__init__():", self, attribute)
self.attribute = attribute
test1 = demoClass("abc")
test2 = demoClass("xyz")
print(test1.number, test1.instances_created)
print(test2.number, test2.instances_created)
输出:
__new__(): <class '__main__.demoClass'> ('abc',) {}
__init__(): <__main__.demoClass object at 0x01894690> abc
__new__(): <class '__main__.demoClass'> ('xyz',) {}
__init__(): <__main__.demoClass object at 0x018946B0> xyz
0 2
1 2
3. __repr__ 返回类描述;__getitem__返回对象的元素
import collections
# 将纸牌定义为具名元组,每个纸牌都有等级和花色
Card = collections.namedtuple('Card', 'rank suit')
class FrenchDeck:
# 等级2-A
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
# 花色红黑方草
suits = 'spades diamonds clubs hearts'.split()
# 构建纸牌
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]
# 获取纸牌
def __getitem__(self, position):
return self._cards[position]
def __repr__(self):
return "纸牌定义"
print(FrenchDeck())
print(FrenchDeck()[0])
输出:
纸牌定义
Card(rank='2', suit='spades')
4 迭代类:
class listDemo:
def __init__(self):
self.__date = []
self.__step = 0
def __next__(self):
if self.__step <= 0:
raise StopIteration
self.__step -= 1
# 返回下一个元素
return self.__date[self.__step]
def __iter__(self):
# 实例对象本身就是迭代器对象,因此直接返回 self 即可
return self
# 添加元素
def __setitem__(self, key, value):
self.__date.insert(key, value)
self.__step += 1
mylist = listDemo()
mylist[0] = 1
mylist[1] = 2
print('iter..', next(mylist))
for i in mylist:
print(i)
输出
iter.. 2
1