Python学习基础笔记六十四——Item系列
1、getitem/setitem/delitem系统:
class Foo:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def __getitem__(self, item):
if hasattr(self, item):
return self.__dict__[item]
def __setitem__(self, key, value):
self.__dict__[key] = value
def __delitem__(self, key):
self.__dict__[key]
f = Foo(egon, 38, 男)
print(f[name])
f[hobby] = 男
print(f[hobby], f.hobby)
# del f.hobby
print(f.__dict__)
del f[hobby]
print(f.__dict__)
2、new例:
class A:
def __init__(self):
self.x = 1
print(in init function)
def __new__(cls, *args, **kwargs):
print(in new function)
return object.__new__(A)
a = A()
print(a.x)
3、单例模式:
class Singleton:
def __new__(cls, *args, **kw):
if not hasattr(cls, _instance):
cls._instance = object.__new__(cls)
return cls._instance
one = Singleton()
two = Singleton()
two.a = 3
print(one.a)
# 3
# one和two完全相同,可以用id(), ==, is检测
print(id(one))
# 29097904
print(id(two))
# 29097904
print(one == two)
# True
print(one is two)
3、__eq__
class A:
def __init__(self, name):
self.name = name
def __eq__(self, other):
if self.name == other.name:
return True
else:
return False
obj1 = A(eggon)
obj2 = A(egg)
print(obj1 == obj2)
4、__hash__
class A:
def __init__(self):
self.a = 1
self.b = 2
def __hash__(self):
return hash(str(self.a)+str(self.b))
a = A()
print(hash(a))
