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 ...
随机推荐
- Python 基础知识(二)
一.基础数据类型 1.数字int 数字主要是用于计算用的,使用方法并不是很多,就记住一种就可以: #bit_length() 当十进制用二进制表示时,最少使用的位数 # -*- coding:UTF- ...
- Ubuntu16.04下安装配置numpy,scipy,matplotlibm,pandas 以及sklearn+深度学习tensorflow配置+Keras2.0.6(非Anaconda环境)
1.ubuntu镜像源准备(防止下载过慢): 参考博文:http://www.cnblogs.com/top5/archive/2009/10/07/1578815.html 步骤如下: 首先,备份一 ...
- 0004python中的map,reduce,lambda,filter
编程实现:a[0]*b[0] + a[1]*b[1] +...+a[i]*b[j] >>> a=[1,2,3,4,5]>>> b=[6,7,8,9,0] >& ...
- 使用Lotus Enterprise Integrator (LEI)将Domino附件移至关系数据库(图文过程)
参考IBM解决方案:http://www.ibm.com/developerworks/cn/lotus/LEI-attachments/index.html 转载请注明出处:http://blog. ...
- redhat7下对用户账户的管理
redhat7对用户帐号的管理主要集中在新建,删除和修改三个动作. 1.新建用户 通过useradd --help,我们得到useradd的详细参数. -d 目录 指定用户主目录,如果此目录不存在,则 ...
- tomcat访问
1:html页面或者需要访问的对象需要放置到webapps/ROOT下面既可以 http://localhost:8080/直接访问 2:
- Weka——PrincipalComponents分析
package weka.filters.unsupervised.attribute; PrincipalComponents 属性: /** The data to transform analy ...
- soapUI-Conditional Goto
1.1.1 Conditional Goto 1.1.1.1 概述 - Conditional Goto Conditional Goto TestStep包含任意数量的XPath/JSONPath ...
- isKindOfClass isMemeberOfClass 的区分
isKindOfClass If you use such constructs in your code, you might think it is alright to modify an ob ...
- 评价指标的局限性、ROC曲线、余弦距离、A/B测试、模型评估的方法、超参数调优、过拟合与欠拟合
1.评价指标的局限性 问题1 准确性的局限性 准确率是分类问题中最简单也是最直观的评价指标,但存在明显的缺陷.比如,当负样本占99%时,分类器把所有样本都预测为负样本也可以获得99%的准确率.所以,当 ...