高渐飞 发表于 2018-7-18 20:51:49

A-19-魔法方法

#coding=UTF-8

#知识点总结
"""
1.魔法方法详解 http://bbs.fishc.org/thread-48793-1-1.html
2.__new__(cls [, ...]): 是一个对象实例化时所调用的第一个方法, 第一个参数是类(cls), 其他参数会直接传递给__init__方法
__new__ 返回实例对象, 通常是参数cls这个参数的实例化对象, 也可以返回其他对象.

3. __init__(self [, ...]): 当实例对象有明确的初始化步骤时改写__init__()
4. __del__(self): 当对象将被销毁的时候调用, 销毁指的是垃圾回收机制回收这个对象

5.python3以后, int(), float(), list(), str()等工厂函数的调用实际上就是创建类的实例化对象的过程, 工厂函数就是类对象

6.当对实例对象进行算术运算时, 会自动调用算术运算的魔法方法

      运算符                   对应的魔法方法
      +                __add__(self, other)
      -                __sub__(self, other)
      *                __mul__(self. other)
      /                __truediv__(self, other)
      //               __floordiv__(slef, other)
      %                __mod__(self, other)
      **               __pow__(self, other[, modulo])
      <<               __lshift__(self, other)
      >>               __rshift__(slef, other)
      &                __and__(self, other)
      ^                __xor__(self, other)
      |                __or__(self, other)


    例如, 当 a + b 时, 会自动调用 __add__() 方法, 可以通过修改魔法方法来自定义算术运算
"""


#1.
class CapStr(str):   #定义一个继承自str的类
    def __new__(cls,string):
      string = srting.upper()
      return str.__new__(cls,string)
a=CapStr("I love you")
print(a)

#2.
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)
print(rect.getperi())
print(rect.getarea())

#3.
class C:
    def __init__(self):
      print("我是_init_方法,我被调用了....")
    def __del__(self):
      print("我是_del_方法,我被调用了....")
c1=C()
c2=c1
c3=c2
del c3
del c2
del c1

#4.
class Try_int(int):
    def __add__(self, other):
      return int (self) + int(other)
    def __sub__(self, other):
      returnint(self) - int(other)

a=Try_int(3)
b=Try_int(5)
print(a+b)

#5.
classNint(int):
    def__new__(cls, arg = 0):
      iftype(arg) == type(str):
            total = 0
            for each_str in arg:
               total += ord(each_str)

            arg = total
      return int.__new__(cls, arg)


#6. 反运算的魔法方法,当左操作数不支持相应操作时被调用
#例如__radd__, a + b, 当a对象没有__add__方法时, b对象才会调用__radd__:
class Nint(int):
    def __radd__(self, other):
      print("__radd__ 被调用了!")
      return int.__sub__(self, other)

a = Nint(5)
b = Nint(3)
print(a+b)
print(1 + b) #调用__radd__(self, other),其中self为b,other为1
print(3-a)   #这是自动调用的是_sub_函数,即__sub__(3, a)

class Nint(int):
    def __rsub__(self, other):
      return int.__sub__(self,other)
a=Nint(5)
print(3-a)    #调用函数__rsub__(self, other),其中self为a


#


"""
#在继承的类中调用基类的方法, 使用super()

#对于修饰符@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()
# 静态方法只在内存中生成一个,节省开销
print(c1.static is C.static)
print(c1.nostatic is C.nostatic)
print(c1.static)
print(c2.static)
print(C.static)

# 普通方法每个实例对象都拥有独立的一个,开销较大
print(c1.nostatic)
print(c2.nostatic)
print(C.nostatic)
print(c1.static(1, 2, 3))
print(C.static(1, 2, 3))

"""
页: [1]
查看完整版本: A-19-魔法方法