博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
内置方法
阅读量:6948 次
发布时间:2019-06-27

本文共 3411 字,大约阅读时间需要 11 分钟。

 

 

七、__setitem__,__getitem__,__delitem__

 

class Foo:    def __init__(self,name):        self.name=name    def __getitem__(self, item):        print(self.__dict__[item])    def __setitem__(self, key, value):        self.__dict__[key]=value    def __delitem__(self, key):        print('del obj[key]时,我执行')        self.__dict__.pop(key)    def __delattr__(self, item):        print('del obj.key时,我执行')        self.__dict__.pop(item)        # self.pop(item)      #  没有__dict__会报错,__dict__对应对象内部变量f1=Foo('sb')f1['age']=18f1['age1']=19print(f1.__dict__)      #{'name': 'sb', 'age': 18, 'age1': 19}del f1.age1             #del obj.key时,我执行del f1['age']           #del obj[key]时,我执行f1['name']='alex'print(f1.__dict__)      #{'name': 'alex'}
View Code

 

八、__str__,__repr__,__format__

 

#_*_coding:utf-8_*_# __author__ = 'Linhaifeng'format_dict={    'nat':'{obj.name}-{obj.addr}-{obj.type}',#学校名-学校地址-学校类型    'tna':'{obj.type}:{obj.name}:{obj.addr}',#学校类型:学校名:学校地址    'tan':'{obj.type}/{obj.addr}/{obj.name}',#学校类型/学校地址/学校名}class School:    def __init__(self,name,addr,type):        self.name=name        self.addr=addr        self.type=type    def __repr__(self):        return 'School(%s,%s)' %(self.name,self.addr)    def __str__(self):        return '(%s,%s)' %(self.name,self.addr)    def __format__(self, format_spec):        # if format_spec        if not format_spec or format_spec not in format_dict:            format_spec='nat'        fmt=format_dict[format_spec]        return fmt.format(obj=self)s1=School('oldboy1','北京','私立')print('from repr: ',repr(s1))       #from repr:  School(oldboy1,北京)print('from str: ',str(s1))         #from str:  (oldboy1,北京)print(s1)                           #(oldboy1,北京)   走的是__str__'''str函数或者print函数--->obj.__str__()repr或者交互式解释器--->obj.__repr__()如果__str__没有被定义,那么就会使用__repr__来代替输出注意:这俩方法的返回值必须是字符串,否则抛出异常'''print(format(s1,'nat'))     #oldboy1-北京-私立print(format(s1,'tna'))     #私立:oldboy1:北京print(format(s1,'tan'))     #私立/北京/oldboy1print(format(s1,'asfdasdffd'))  #oldboy1-北京-私立
View Code

自定义format练习

date_dic={    'ymd':'{0.year}:{0.month}:{0.day}',    'dmy':'{0.day}/{0.month}/{0.year}',    'mdy':'{0.month}-{0.day}-{0.year}',}class Date:    def __init__(self,year,month,day):        self.year=year        self.month=month        self.day=day    def __format__(self, format_spec):        if not format_spec or format_spec not in date_dic:            format_spec='ymd'        fmt=date_dic[format_spec]        return fmt.format(self)d1=Date(2016,12,29)print(format(d1))print('{:mdy}'.format(d1))      #{:} 冒号前面是格式引导符,后面是格式符
View Code
  • issubclass和isinstance

class A:    passclass B(A):    passprint(issubclass(B,A)) #B是A的子类,返回Truea1=A()print(isinstance(a1,A)) #a1是A的实例
View Code

九、slots

1.__slots__是什么:是一个类变量,变量值可以是列表,元祖,或者可迭代对象,也可以是一个字符串(意味着所有实例只有一个数据属性) 2.引子:使用点来访问属性本质就是在访问类或者对象的__dict__属性字典(类的字典是共享的,而每个实例的是独立的) 3.为何使用__slots__:字典会占用大量内存,如果你有一个属性很少的类,但是有很多实例,为了节省内存可以使用__slots__取代实例的__dict__ 当你定义__slots__后,__slots__就会为实例使用一种更加紧凑的内部表示。实例通过一个很小的固定大小的数组来构建,而不是为每个实例定义一个 字典,这跟元组或列表很类似。在__slots__中列出的属性名在内部被映射到这个数组的指定小标上。使用__slots__一个不好的地方就是我们不能再给 实例添加新的属性了,只能使用在__slots__中定义的那些属性名。 4.注意事项:__slots__的很多特性都依赖于普通的基于字典的实现。另外,定义了__slots__后的类不再 支持一些普通类特性了,比如多继承。大多数情况下,你应该 只在那些经常被使用到 的用作数据结构的类上定义__slots__比如在程序中需要创建某个类的几百万个实例对象 。 关于__slots__的一个常见误区是它可以作为一个封装工具来防止用户给实例增加新的属性。尽管使用__slots__可以达到这样的目的,但是这个并不是它的初衷。           更多的是用来作为一个内存优化工具。

 

转载于:https://www.cnblogs.com/wenyule/p/9117665.html

你可能感兴趣的文章
初始化参数绑定——日期格式
查看>>
python 基础 10.0 nosql 简介--redis 连接池及管道
查看>>
【SP1811】 LCS - Longest Common Substring(SAM)
查看>>
Backup: Array in Perl6
查看>>
ansible常用模块
查看>>
【C++】typeinfo.h
查看>>
Asp.net使用powershell管理hyper-v
查看>>
ASP.NET(C#)图片加文字、图片水印(转)
查看>>
python 爬虫
查看>>
连接ssh反应很慢,卡,延迟
查看>>
rabbitmq基本操作
查看>>
疑问????
查看>>
Leetcode 515. Find Largest Value in Each Tree Row
查看>>
WINCE 下载地址(转)
查看>>
日期操作积累
查看>>
Linux 僵尸进程的筛选和查杀
查看>>
WP7基础学习---第十五讲
查看>>
mysql linux app
查看>>
DotNetCore学习-3.管道中间件
查看>>
Python基础11_函数名运用,闭包,迭代器
查看>>