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

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

一、概述:

  python魔法方法:

    类中被双下划线包围的方法,例如__init__(self, ...)

    魔法方法是面向对象的python的一切  

1 >>> class R(object):2 ...     def __init__(self, x, y):3 ...             self.x = x4 ...             self.y = y5 ...     def get(self):6 ...             return (self.x + self.y)7 ...     def getA(self):8 ...             return self.x * self.y

  在实例化类时,__init__()并不是第一个被调用的函数,第一个被调用的函数是__new__();

1 >>> class Capstr(str):        #str是不可改变对象2 ...     def __new__(cls, string):       #自定义的重写__new__函数3 ...             string = string.upper()4 ...             return str.__new__(cls, string)5 ...     6 ... 7 >>> a = Capstr("hello")8 >>> print a9 HELLO

  __del__():相当于c++里面的析构函数;

1 >>> class C(object): 2 ...     def __init__(self): 3 ...             print "__init__ is calling" 4 ...     def __del__(self): 5 ...             print "__del__ is calling" 6 ...  7 >>> a = C() 8 __init__ is calling 9 >>> b = a10 >>> c = a11 >>> d = a12 >>> del b13 >>> del a14 >>> del d15 >>> del c              #当引用个数为0时候,启用python垃圾回收机制,__del__方法被调用16 __del__ is calling

 python内置方法实例:

1 >>> class New_int(int): 2 ...     def __add__(self, other): 3 ...             return int.__sub__(self, other) 4 ...     def __sub__(self, other): 5 ...             return int.__add__(self, other) 6 ...  7 >>> a = New_int(3) 8 >>> b = New_int(5) 9 >>> a + b10 -2

python内置方法总结:

转载地址:http://gxabl.baihongyu.com/

你可能感兴趣的文章
书法家程序员往往是公司最不受欢迎的程序员
查看>>
关于文件操作集锦 delphi
查看>>
mysqldump备份还原和mysqldump导入导出语句大全详解 转
查看>>
WAMP 隐藏服务器信息
查看>>
【APP打开小程序】
查看>>
CentOS7.1配置Ceph集群环境
查看>>
Ceph常用命令
查看>>
Spring MVC3 一对多的复杂表单和一次保存方法
查看>>
R.java檔重建
查看>>
Java注解Annotation详解
查看>>
ejb事务
查看>>
node环境搭建
查看>>
Speed ScrollView
查看>>
BJImageCropper
查看>>
android handler总结
查看>>
2. ASIHttpRequest-发送数据
查看>>
[应用模板]移动应用界面
查看>>
嵌入式Linux C编程 02
查看>>
sql server支持连接管理功能
查看>>
java的强制类型转换想到的
查看>>