面向对象 构造方法, 析构 及 内置


# ========================= 构造方法 , 析构方法, 初始化
# 构造方法 创建一个对象的
# 初始化方法 __init__ 给已经创建出来的对象添加属性
# 析构方法 删除一个对象的时候调用的方法
# import time
# class A:
# def __init__(self):
# self.f = open('userinfo','a')
# def consume(self):
# pass
# def __del__(self):
# '''在删除一个对象之前做一些收尾工作'''
# self.f.close()
# print('删除一个对象的时候调用我')
#
# a = A()
# time.sleep(1)
# del a
# # 删除一个对象的时候,如果内部存在__del__方法,
# # 那么在删除一个对象之前先执行__del__方法中的代码
# print(a)

# ========================= __new__ 构造方法 =====================
# new一个对象
# object.__new__()
# class A:
# def __init__(self):
# print('执行init方法了')
# def __new__(cls):
# print('执行new方法了')
# return object.__new__(cls) # 创造对象,将对象返回
#
# a = A()
# print(type(a))
# print(type(A))
# 先执行__new__方法 创造出一个对象
# 然后把创造出来的对象传递给__init__方法
# 会把self自动的返回,被a接收


# 元类
# 有一个元类 在创建类
# type() 所有直接用class创建出来的类的元类都是type

# class 类名(B,metaclass=type = 元类名)
# class 类名(B,metaclass=type) # 默认

# 元类 创造 类 所以所有的类的type都是它的元类,默认是type
# 类 创造 对象 具体创造对象的方法 __new__方法,所有的对象的type都是它对应的类

# python中 一切皆对象
# 变量 都有它属于的数据类型

# 设计模式
# 单例模式
# 一个类 可以被多次实例化 但是同一时间在python的内存中,只能有一个实例
# class A:
# _instance = None
# def __init__(self,name):
# '''给娃穿衣服'''
# self.name = name
# def __new__(cls, *args, **kwargs):
# '''生娃的过程'''
# if not A._instance:
# A._instance = object.__new__(cls)
# return A._instance
# a1 = A('alex') # 第一次实例化的时候创造一个实例
# print(a1.name)
# a2 = A('egon')
# print(a1.name,a2.name) # 'alex' 'alex'

# class A:
# def __init__(self,name):
# '''给娃穿衣服'''
# self.name = name
# def __new__(cls, *args, **kwargs):
# '''生娃的过程'''
# if not hasattr(A,'_instance'):
# A._instance = object.__new__(cls)
# return A._instance
# a1 = A('alex') # 第一次实例化的时候创造一个实例
# print(a1.name)
# a2 = A('egon')
# print(a1.name,a2.name) # 'alex' 'alex'

# class A:
# name = 'Alex'
# @classmethod
# def func(cls):
# pass
# A.name = 'Egon'

### = item 系列
# class A:
# def __init__(self,name):
# self.name = name
# self.age = 81
# def __getitem__(self, item): #a["name"] 就是自动调用了getitem 方法
# return self.__dict__[item]
# def __setitem__(self, key, value): # 增加一个属性
# self.__dict__[key] = value
# def __delitem__(self, key): # 删除一个属性
# del self.__dict__[key]
# a = A('alex')

# print(a['name']) # 对应了类中一个方法的语法
# a.name
# print(a['age']) # 对应了类中一个方法的语法
# a.age
# 增加 和 修改一个属性
# a['sex'] = '不详'
# # a.sex = '不详'
# print(a.__dict__)
# # print(a.sex)
# # print(a['sex'])
# a['sex'] = '女'
# print(a.__dict__)
# del a['sex']
# print(a.__dict__)

# -- call
# class A:
# def __init__(self,):
# print("s")
# def __call__(self,a):
# print('执行我了',a,)
# def call(self,a):
# print('执行我了',a,)
# a = A()# 执行
# a('aaa') # 执行__call__
# a.call('aaa')

# ========== __hash__
# hash
# 不可变的数据类型都可以被hash
# dic = {"name":"alex"}
# class A:
# def __hash__(self):
# return object.__hash__(self)
# a = A()
# b = A()
# print(hash(dic["name"])) # object.__hash__()
# print(hash(a)) # object.__hash__()
# print(hash(a)) # object.__hash__()
# print(hash(a)) # object.__hash__()
# print(hash(a)) # object.__hash__()
# print(hash(a)) # object.__hash__()
# print(hash(a)) # object.__hash__()
# print(hash(b)) # object.__hash__()

# dict的key set的元素
# dic key --> value
# dic[key] = value
# hash(obj)函数,obj对象对应的类必然内部实现了__hash__方法
# hash的结果就是__hash__方法的返回值
# 且在一次成的执行过程中是不会发生变化的
# 且要想作为字典的key或者作为集合的元素,这个对象对应的类必须实现__hash__方法

# 面试题 ###
# 金融公司面试题
# 有一个类,对应这个类产生了100个对象
# 每个对象有三个属性 : 姓名 年龄 性别
# 请对这一百个对象进行去重,如果姓名和性别相同,即便年龄不同也是相同的对象
# 问最简便的方法?
# class Person:
# def __init__(self,name,age,sex):
# self.name = name
# self.age = age
# self.sex = sex
# def __hash__(self):
# return hash('%s%s'%(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(100):
# p_lst.append(Person('egon',i,'male'))
# p_lst.append(Person('alex',i,'male'))
# p_lst.append(Person('yuan',i,'male'))
# print(p_lst)
# print(set(p_lst)) # 报错不可hash 完成了__hash__
# class Person:
# def __init__(self,name,age,sex):
# self.name = name
# self.age = age
# self.sex = sex
# def __eq__(self, other):
# if self.name == other.name and
# self.sex == other.sex:
# return True
# def __hash__(self):
# return hash("%s%s"%(self.name,self.sex))
# p_lst = []
# for i in range(100):
# p_lst.append(Person("alex",i,"male"))
# print(set(p_lst))

# hash是否相等 __hash__
# 值是否相等 __eq__

# 收获1
# 对于一些python当中已经存在的内置函数 内置数据类型 内置模块中的方法
# 都有可能依赖于类中的内置方法
# 收获2
# set方法依赖集合中元素对象的__hash__ __eq__

# = 纸牌实例
# 数据结构与算法 python 数据结构
# python核心编程第二三版 基础
# 流畅的python 进阶
# from collections import namedtuple
# Card = namedtuple('Card',['rank','suit'])
# # card1 = Card(1,'红桃')
# 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[:])
# print(deck.__dict__)
# from random import choice
# print(choice(deck)) # deck对象对应的类中的getitem方法和len方法
# from random import shuffle
# shuffle(deck)
# print(deck[:])
原文地址:https://www.cnblogs.com/xuerh/p/8562889.html