面向对象进阶-item系列、__new__、__hash__、__eq__ (四)
item系列
dic = {'k':'v'}
# 对象 : 存储属性 和调用方法
dic['k'] = 'v'
# 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__
# __init__ 初始化方法
# __new__ 构造方法 : 创建一个对象
class A:
def __init__(self):
self.x = 1
print('in init function')
# def __new__(cls, *args, **kwargs): 为什么这里是cls而不是self,因为先执行_new_才有self
# print('in new function')
# return object.__new__(A, *args, **kwargs) 执行object后才产生类A
a =A()
print(a)》》》显示 :'in new function' 'in init function'
# a1 = A()
# a2 = A()
# a3 = A()
# print(a1)
# print(a2) a1/a2/a3打印出的内存地址不一样,多个类对象的内存空间
# print(a3)
# print(a.x)
# 设计模式
# 23种
# 单例模式
# 一个类 始终 只有 一个 实例
# 当你第一次实例化这个类的时候 就创建一个实例化的对象
# 当你之后再来实例化的时候 就用之前创建的对象
# class A:
# __instance = False
# def __init__(self,name,age):
# self.name = name
# self.age = age
# def __new__(cls, *args, **kwargs):
# if cls.__instance: 第二次为真,执行这里
# return cls.__instance
# cls.__instance = object.__new__(cls) cls可不填 第一次__instance为假执行这里,创建对象赋值给cls.__instance
# return cls.__instance
#
# egon = A('egg',38)
# egon.cloth = '小花袄'
# nezha = A('nazha',25)
# print(nezha) 》内存地址一样
# print(egon) 》》内存地址一样
# print(nezha.name) 》nazha
# print(egon.name) 》》nazha
# print(nezha.cloth) 》》'小花袄'
__eq__
# class A:
# def __init__(self,name):
# self.name = name
#
# def __eq__(self, other): eq方法
# if self.__dict__ == other.__dict__:
# return True
# else:
# return False
#
# ob1 = A('egon')
# ob2 = A('egg')
# print(ob1 == ob2) 》》False 没有__eq__时默认比较内存地址,等于不成立false
__hash__哈希
# hash() 哈希值,不同对象,哈希值不同
# class A:
# def __init__(self,name,sex):
# self.name = name
# self.sex = sex
# def __hash__(self): 哈希值是否相等由自定义hash来控制,不走内置hash()
# return hash(self.name+self.sex)
#
# a = A('egon','男')
# b = A('egon','nv')
# c = A('egon','nv')
# print(hash(a))
# print(hash(b))
# print(hash(c)) b和c哈希值一样
import json
from collections import namedtuple
Card = namedtuple('Card',['rank','suit']) # rank 牌面的大小 suit牌面的花色(这个相当于一个只有属性的类)
C1=Card(2,"红心")》print(C1)》Card(rank=2,suit="红心")(实例化)
# class FranchDeck:
# ranks = [str(n) for n in range(2,11)] + list('JQKA') # 2-A
# suits = ['红心','方板','梅花','黑桃']
#
# def __init__(self):
# self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
# for suit in FranchDeck.suits]
解释》》for suit in FranchDeck.suits
for rank in FranchDeck.rangks 》》》
Card(suit,rank) 《《

#
# def __len__(self):
# return len(self._cards)
#
# def __getitem__(self, item):
# return self._cards[item]
#
# def __setitem__(self, key, value):
# self._cards[key] = value
#
# def __str__(self):
# return json.dumps(self._cards,ensure_ascii=False)
# deck = FranchDeck()
# print(deck[10])
# from random import choice
# print(choice(deck)) choice依赖_len_方法
# # print(choice(deck))
# from random import shuffle
# shuffle(deck) shuffle依赖setitem方法
# print(deck[10])
# print(deck)
# print(deck[:5]) #切片,利用items系列
# 内置函数 内置的模块 内置的基础类型 < --- >类的内置方法
# == 》》内置调用 __eq__
# len() 》》内置调用__len__
# 100 名字 和 性别 年龄不同
# set 集合,可以去重
# class A:
# def __init__(self,name,sex,age):
# self.name = name
# self.sex = sex
# self.age = age
#
# # def __eq__(self, other):
# # if self.name == other.name and self.sex == other.sex:
# # return True
# # return False
#
# def __hash__(self):
# return hash(self.name + self.sex)
# a = A('egg','男',38)
# b = A('egg','男',37)
# print(set((a,b))) # unhashable(是不可哈希意思)
# set 依赖对象的 hash eq
面向对象进阶-item系列、__new__、__hash__、__eq__ (四)的更多相关文章
- 面向对象的进阶(item系列,__new__,__hash__,__eq__)
面向对象的进阶(item系列,__new__,__hash__,__eq__) 一.item系列 getitem.setitem.delitem(操作过程达到的结果其实就是增删改查) class ...
- python面向对象( item系列,__enter__ 和__exit__,__call__方法,元类)
python面向对象进阶(下) item系列 __slots__方法 __next__ 和 __iter__实现迭代器 析构函数 上下文管理协议 元类一.item系列 把对象操作属性模拟成字典的 ...
- __del__,item系列 ,hash方法,__eq__,
# 构造方法 申请一个空间# 析构方法 释放一个空间 # 某个对象借用了操作系统的资源,还要通过析构方法归还回去:文件资源 网络资源 # 垃圾回收机制 class A: def __del__(sel ...
- python 全栈开发,Day24(复习,__str__和__repr__,__format__,__call__,__eq__,__del__,__new__,item系列)
反射: 使用字符串数据类型的变量名来使用变量 wwwh即what,where,why,how 这4点是一种学习方法 反射 :使用字符串数据类型的变量名来使用变量 1.文件中存储的都是字符串 2.网络 ...
- 1、__del__ 2、item系列 3、__hash__ 4、__eq__
1.__del__ 析构方法 释放一个空间之前之前 垃圾回收机制 2.item系列 和对象使用[ ]访问值有联系 __getitem__ __setitem__ __delit ...
- day7--面向对象进阶(内含反射和item系列)
一面向对象的结构和成员 1.1面向对象的结构 class A: company_name = '老男孩教育' # 静态变量(静态字段) __iphone = '1353333xxxx' # 私有静态变 ...
- [.net 面向对象程序设计进阶] (25) 团队开发利器(四)分布式版本控制系统Git——使用GitStack+TortoiseGit 图形界面搭建Git环境
[.net 面向对象程序设计进阶] (25) 团队开发利器(四)分布式版本控制系统Git——使用GitStack+TortoiseGit 图形界面搭建Git环境 本篇导读: 前面介绍了两款代码管理工具 ...
- 面向对象 反射 和item系列和内置函数和__getattr__和__setattr__
反射 反射主要用在网络编程中, python面向对象的反射:通过字符串的形式操作对象相关的属性.python的一切事物都是对象. 反射就是通过字符串的形式,导入模块:通过字符串的形式,去模块寻找指定函 ...
- python进阶(7):面向对象进阶
学了面向对象三大特性继承,多态,封装.今天我们看看面向对象的一些进阶内容,反射和一些类的内置函数. 一.isinstance和issubclass class Foo: pass class Son( ...
随机推荐
- php iframe 上传文件
我们通过动态的创建iframe,修改form的target,来实现无跳转的文件上传. 具体的实现步骤 1.捕捉表单提交事件 2.创建一个iframe 3.修改表单的target,指向iframe ...
- Oracle登录命令
1.运行SQLPLUS工具 C:\Users\wd-pc>sqlplus 2.直接进入SQLPLUS命令提示符 C:\Users\wd-pc>sqlplus /nolog 3.以OS身份连 ...
- python中的日志模块logging
1.日志级别5个: 警告Warning 一般信息Info 调试 Debug 错误Error 致命Critical 2.禁用日志方法 logging.disable(logging.DEBUG) 3 ...
- 6. Manage the driver for browser and the script for Hub
- 3层+SVN学习笔记(1)
public List<MemberTypeInfo> GetList() { //查询未删除的数据 string sql = "select * from memberType ...
- 492. Construct the Rectangle
static int wing=[]() { std::ios::sync_with_stdio(false); cin.tie(NULL); ; }(); class Solution { publ ...
- 201709021工作日记--Volley源码解读(四)
接着volley源码(三)继续,本来是准备写在(三)后面的,但是博客园太垃圾了,写了半天居然没保存上,要不是公司这个博客还没被限制登陆,鬼才用这个...真是垃圾 继续解读RequestQueue的源码 ...
- SDK | 声波传输
SDK | 声波传输 - 音频流生成 https://github.com/CloudSide/WaveTransSdk/tree/master/c/freq_util Objective-C: ht ...
- 从Google Earth 中下载三维模型
https://www.cnblogs.com/chidou-yin/p/4306224.html
- C++中的关键字用法---typename
1. typename 关键字 "typename"是一个C++程序设计语言中的关键字.当用于泛型编程时是另一术语"class"的同义词.这个关键字用于指出模板 ...