|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 风不会停息 于 2018-7-5 14:37 编辑
1. python 魔法方法详解: http://bbs.fishc.com/thread-48793-1-1.html
2. 对于反运算的魔法方法, 例如__radd__, a + b, 当a对象没有__add__方法时, b对象才会调用__radd__:
- >>> class Nint(int):
- def __radd__(self, other):
- print("__radd__ 被调用了!")
- return int.__add__(self, other)
- >>> a = Nint(5)
- >>> b = Nint(3)
- >>> a + b
- 8
- >>> 1 + b
- __radd__ 被调用了!
- 4
复制代码
3. 在继承的类中调用基类的方法, 使用super()
4. 对于修饰符@staticmethod, 表示紧跟的一个方法为静态方法, 静态方法不会绑定到实例对象上, 可以节省开销, 所以定义静态方法时不需要传入self参数, 当对象访问时也不会传入self参数, 例如:
- class C:
- @staticmethod # 该修饰符表示 static() 是静态方法
- def static(arg1, arg2, arg3):
- print(arg1, arg2, arg3, arg1 + arg2 + arg3)
- def nostatic(self):
- print("I'm the f**king normal method!")
复制代码
- >>> c1 = C()
- >>> c2 = C()
- # 静态方法只在内存中生成一个,节省开销
- >>> c1.static is C.static
- True
- >>> c1.nostatic is C.nostatic
- False
- >>> c1.static
- <function C.static at 0x03001420>
- >>> c2.static
- <function C.static at 0x03001420>
- >>> C.static
- <function C.static at 0x03001420>
- # 普通方法每个实例对象都拥有独立的一个,开销较大
- >>> c1.nostatic
- <bound method C.nostatic of <__main__.C object at 0x03010590>>
- >>> c2.nostatic
- <bound method C.nostatic of <__main__.C object at 0x032809D0>>
- >>> C.nostatic
- <function C.nostatic at 0x0328D2B8>
复制代码
- >>> c1.static(1, 2, 3)
- 1 2 3 6
- >>> C.static(1, 2, 3)
- 1 2 3 6
复制代码 |
|