Métodos mágicos relacionados con el operador
Puede definir el método de cálculo usted mismo
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
# if self.name==other.name and self.age ==other.age:
# return True
# return False
return self.name == other.name and self.age == other.age
def __gt__(self, other):
return self.age > other.age
# def __ge__(self, other):# >=
def __lt__(self, other):# <
return self.age < other
# def __le__(self, other):# <=
# def __add__(self, other):# 加法会自动调这个
# def __sub__(self, other):# 减法会自动调这个
# def __mul__(self, other):# 乘法自动调这个
# def __truediv__(self, other):# 除法自动调这个
p1 = Person('张三', 18)
p2 = Person('张三', 18)
# p1和p2是同一个对象吗?
# 怎么比较两个对象是否是同一个对象?比较的是内存地址
print('0x%x' % id(p1))
print('0x%x' % id(p2))
# is 身份运算符 可以用来判断两个对象是否是同一个对象
# is 是用来比较两个对象的内存地址的
print('p1 is p2', p1 is p2)# False
# 如果__eq__不重写,那么默认比较的还是内存地址,p1.__eq__(p2)
# 就看你想让他们的什么属性进行比较了
print('p1 == p2', p1 == p2) # True
print(p1 > p2)# False
print(p1 < 20)# True
No es solo una comparación entre objetos de instancia, sino también otros tipos de datos, según sus necesidades.
Propiedades integradas
Hay muchas propiedades integradas, por lo que no las enumeraré todas
class Person(object):
"""
这是一个人
"""
def __init__(self, name, age):
self.name = name
self.age = age
p = Person('张三', 18)
print(dir(p))
print(p.__class__) # <class '__main__.Person'>
print(p.__dict__) # {'name': '张三', 'age': 18}把对象属性和值转换成一个字典
print(p.__dir__()) # 等价于内置函数dir
print(p.__module__)# 模块名
print(p.__doc__)# 注释
"""
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']
<class '__main__.Person'>
{'name': '张三', 'age': 18}
['name', 'age', '__module__', '__doc__', '__init__', '__dict__', '__weakref__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
__main__
这是一个人
"""
Usa el objeto como diccionario
(Como entendimiento, no muy útil)
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, item):
return self.__dict__[item]
p = Person('张三', 18)
print(p.__dict__) # 将对象转换成字典,{'name': '张三', 'age': 18}
k = p.__dict__
k['name'] = '李四'
print(k)
p.age = 19
print(p.__dict__)
# 不能直接把一个对象当做字典来使用 是要去重写这两个方法
# p['age'] = 19 # 修改字典值[]方法会自动调用对象的__setitem__方法
# print(p.__dict__)
# print(p['name'])# 获取字典值得时候回自动调用__getitem__方法