item系列
__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):
del self.__dict__[key] f = Foo('egon',38,'男')
print(f['name'])
f['hobby'] = '男'
print(f.hobby,f['hobby'])
del f.hobby # object 原生支持 __delattr__
del f['hobby'] # 通过自己实现的
print(f.__dict__)
__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, *args, **kwargs) a = A()
print(a.x)
单例模式:
class Singleton:
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls, *args, **kw)
return cls._instance one = Singleton()
two = Singleton() two.a = 3
print(one.a)
#
# one和two完全相同,可以用id(), ==, is检测
print(id(one))
#
print(id(two))
#
print(one == two)
# True
print(one is two)
单例模式
一个类 始终 只有 一个 实例
# 当你第一次实例化这个类的时候 就创建一个实例化的对象
# 当你之后再来实例化的时候 就用之前创建的对象
__call__
对象后面加括号,触发执行。
注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
class Foo: def __init__(self):
pass def __call__(self, *args, **kwargs): print('__call__') obj = Foo() # 执行 __init__
obj() # 执行 __call__
__len__
class A:
def __init__(self):
self.a = 1
self.b = 2 def __len__(self):
return len(self.__dict__)
a = A()
print(len(a))
__eq__
class A:
def __init__(self):
self.a = 1
self.b = 2 def __eq__(self,obj):
if self.a == obj.a and self.b == obj.b:
return True
a = A()
b = A()
print(a == b)
class FranchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = ['红心','方板','梅花','黑桃'] def __init__(self):
self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
for suit in FranchDeck.suits] def __len__(self):
return len(self._cards) def __getitem__(self, item):
return self._cards[item] deck = FranchDeck()
print(deck[0])
from random import choice
print(choice(deck))
print(choice(deck)) 纸牌游戏
纸牌游戏
class FranchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = ['红心','方板','梅花','黑桃'] def __init__(self):
self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
for suit in FranchDeck.suits] def __len__(self):
return len(self._cards) def __getitem__(self, item):
return self._cards[item] def __setitem__(self, key, value):
self._cards[key] = value deck = FranchDeck()
print(deck[0])
from random import choice
print(choice(deck))
print(choice(deck)) from random import shuffle
shuffle(deck)
print(deck[:5])
纸牌游戏2
class Person:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex def __hash__(self):
return hash(self.name+self.sex) def __eq__(self, other):
if self.name == other.name and self.sex == other.sex:return True p_lst = []
for i in range(84):
p_lst.append(Person('egon',i,'male')) print(p_lst)
print(set(p_lst))
面试必备-->100 名字和性别相同视为同一人