python 类

一、概述:

  python魔法方法:

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

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

1 >>> class R(object):
2 ...     def __init__(self, x, y):
3 ...             self.x = x
4 ...             self.y = y
5 ...     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 a
9 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 = a
10 >>> c = a
11 >>> d = a
12 >>> del b
13 >>> del a
14 >>> del d
15 >>> 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 + b
10 -2

python内置方法总结:http://www.cnblogs.com/hongfei/p/3858256.html

转载于:https://www.cnblogs.com/chris-cp/p/5068511.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值