python之路----面向对象进阶二
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 名字和性别相同视为同一人
python之路----面向对象进阶二的更多相关文章
- python之路---面向对象编程(二)
类的继承 1.在python3中,只有新式类,新式类的继承方式为:广度优先.而python2中,经典类的继承方式为:深度优先.那么我们来看看深度优先和广度优先的区别吧 如下图,为类之间的继承关系.B, ...
- python之路----面向对象进阶一
一.isinstance和issubclass isinstance(obj,cls)检查是否obj是否是类 cls 的对象 class Foo(object): pass obj = Foo() i ...
- python之路:进阶 二
c = collections.Counter( Counter({ b = collections.Counter( b.update(c) Counter({ Counter({ ...
- Python基础之面向对象进阶二
一.__getattribute__ 我们一看见getattribute,就想起来前面学的getattr,好了,我们先回顾一下getattr的用法吧! class foo: def __init__( ...
- python之路——面向对象进阶
阅读目录 isinstance和issubclass 反射 setattr delattr getattr hasattr __str__和__repr__ __del__ item系列 __geti ...
- python之路 面向对象进阶篇
一.字段 字段包括:普通字段和静态字段,他们在定义和使用中有所区别,而最本质的区别是内存中保存的位置不同, 普通字段属于对象 静态字段属于类 class Province: # 静态字段 countr ...
- Python之路-(Django进阶二)
model: 双下划线: # 获取个数 # # models.Tb1.objects.filter(name='seven').count() # 大于,小于 # # models.Tb1.objec ...
- python之路——面向对象(进阶篇)
面向对象进阶:类成员.类成员的修饰符.类的特殊成员 类成员 类成员分为三大类:字段.方法.属性 一.字段 静态字段 (属于类) 普通字段(属于对象) class City: # 静态字段 countr ...
- 周末班:Python基础之面向对象进阶
面向对象进阶 类型判断 issubclass 首先,我们先看issubclass() 这个内置函数可以帮我们判断x类是否是y类型的子类. class Base: pass class Foo(Base ...
随机推荐
- vue之用法
一.安装 对于新手来说,强烈建议大家使用<script>引入 二. 引入vue.js文件 我们能发现,引入vue.js文件之后,Vue被注册为一个全局的变量,它是一个构造函数. 三.使用V ...
- 7.22 python线程(3)
2018-7-22 10:28:29 回来啦! 6.条件 # !/usr/bin/env python # !--*--coding:utf-8 --*-- # !@Time :2018/7/20 1 ...
- HDU_6033_Add More Zero
Add More Zero Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)T ...
- 【紫书】BigInteger 高精度类型 原书上有一个bug:A+B!=B+A
存个代码 struct BigInterger { static const int BASE = 1e8; ; vector<int> s; BigInterger() { *this ...
- 维基百科 请求流 webrequest_flow
Logstash - Wikitech https://wikitech.wikimedia.org/wiki/Logstash
- mybatis中大于等于、小于等于的写法
在xml格式中,常常会遇到xml解析sql时候出错,这个时候需要用其他符号来表示.在mybatis中会遇到,需要做如下的转换:
- 统计难题---hdu1251字典树模板
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1251 node *head=(node*)malloc(sizeof(node)); for(int ...
- java进程和线程的区别
什么是进程,什么是线程系统要做一件事,运行一个任务,所有运行的任务通常就是一个程序:每个运行中的程序就是一个进程,这一点在任务管理器上面可以形象的看到.当一个程序运行时,内部可能会包含多个顺序执行流, ...
- linux平台mysql密码设置
登录mysql默认没有指定账号 查看默认账号是谁 select user(); mysql> select user();+----------------+| user() |+------- ...
- mac shell终端编辑命令行快捷键
Ctrl + d 删除一个字符,相当于通常的Delete键(命令行若无所有字符,则相当于exit:处理多行标准输入时也表示eof) Ctrl + h 退格删除一个字符,相当 ...