|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
魔法方法总是被双下划线包围,例如__init__
魔法方法是面向对象的Python的一切,如果你不知道魔法方法,说明你还没能意识到面向对象的Python的强大
魔法方法的“魔力”体现在它们总能够在适当的时候被自动调用
1)__init__(self[, ...])类的构造方法,在创建完对象后调用来初始化对象,且规定其返回值为None;
- >>> class Rectangle:
- def __init__(self, x, y):
- self.x = x
- self.y = y
- def getPeri(self):
- return (self.x + self.y) * 2
- def getArea(self):
- return self.x * self.y
-
- >>> rect = Rectangle(3, 4)
- >>> rect.getPeri()
- 14
- >>> rect.getArea()
- 12
- >>> class A:
- def __init__(self):
- return "A fo A.Cup"
-
- >>> a = A()
- Traceback (most recent call last):
- File "<pyshell#16>", line 1, in <module>
- a = A()
- TypeError: __init__() should return None, not 'str'
复制代码
2)__new__(cls[, ...])类的构造方法,在创建对象时调用并返回一个类对象方法,且其调用在__init__方法之前;
- >>> class CapStr(str):
- def __new__(cls, string):
- string = string.upper()
- return str.__new__(cls, string)
-
- >>> a = CapStr("I love FishC.com")
- >>> a
- 'I LOVE FISHC.COM'
复制代码
3)__del__(self) 垃圾回收机制
- >>> class C:
- def __init__(self):
- print("我是__init__方法,我被调用了...")
- def __del__(self):
- print("我是__del__方法,我被调用了...")
-
- >>> c1 = C()
- 我是__init__方法,我被调用了...
- >>> c2 = c1
- >>> c3 = c2
- >>> del c3
- >>> del c2
- >>> del c1
- 我是__del__方法,我被调用了...
复制代码 |
评分
-
查看全部评分
|