Python3 魔法方法:算数运算

1、算数运算的魔法方法

在调用相应的运算符时会自动调用相应的魔法方法

比如a和b相加时(a+b)会自动调用a的__add__魔法方法进行加法操作

如果在a中找不到__add__方法python就会到b中寻找反运算的魔法方法__radd__

2、如何在子类中调用父类的方法

使用super函数

class A:
    def a(self):
        print(‘正在调用A的方法‘)
#AA=A
class B(A):
    def b(self):
        print(‘正在调用B的方法‘)
        #super().a()
        super(B,self).a()

>>> b=B()
>>> b.b()
正在调用B的方法
正在调用A的方法

3、如果希望动态的继承父类(有时候我希望继承A有时候我希望继承B)的方法

只需给基类定义一个别名

class A:
    def a(self):
        print(‘正在调用A的方法‘)
AA=A
class B:
    def b(self):
        print(‘正在调用B的方法‘)
class C(AA):
    def c(self):
        print(‘正在调用C的方法‘)
#如果我想让C继承B只需要将B赋给AA

4、如何使用类的静态属性

class C:
    count = 0  # 静态属性

    def __init__(self):
        C.count = C.count + 1  # 类名.属性名的形式引用

    def getCount(self):
        return C.count

5、如何使用类的静态方法

静态方法的最大优点时不会绑定在实例对象啊,只用一个内存地址节省开销

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!")

例子:

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
<function C.static at 0x06363F60>
>>> c2.static
<function C.static at 0x06363F60>#c1,c2的静态方法内存地址时相同的,而且无绑定对象所以无需self参数,所以对象去访问也不会传入self参数
>>> c1.nostatic
<bound method C.nostatic of <__main__.C object at 0x0635A830>>#非静态方法内存是可变的
>>> c2.nostatic
<bound method C.nostatic of <__main__.C object at 0x0635AFB0>>

 魔法方法详解:http://bbs.fishc.com/thread-48793-1-1.html


魔法方法


含义

 
基本的魔法方法


__new__(cls[, ...])


1. __new__ 是在一个对象实例化的时候所调用的第一个方法
2. 它的第一个参数是这个类,其他的参数是用来直接传递给 __init__ 方法
3. __new__ 决定是否要使用该 __init__ 方法,因为 __new__ 可以调用其他类的构造方法或者直接返回别的实例对象来作为本类的实例,如果 __new__ 没有返回实例对象,则 __init__ 不会被调用
4. __new__ 主要是用于继承一个不可变的类型比如一个 tuple 或者 string


__init__(self[,
...])


构造器,当一个实例被创建的时候调用的初始化方法


__del__(self)


析构器,当一个实例被销毁的时候调用的方法


__call__(self[,
args...])


允许一个类的实例像函数一样被调用:x(a, b) 调用 x.__call__(a, b)


__len__(self)


定义当被 len() 调用时的行为


__repr__(self)


定义当被 repr() 调用时的行为


__str__(self)


定义当被 str() 调用时的行为


__bytes__(self)


定义当被 bytes() 调用时的行为


__hash__(self)


定义当被 hash() 调用时的行为


__bool__(self)


定义当被 bool() 调用时的行为,应该返回 True 或 False


__format__(self,
format_spec)


定义当被 format() 调用时的行为

 
有关属性


__getattr__(self,
name)


定义当用户试图获取一个不存在的属性时的行为


__getattribute__(self,
name)


定义当该类的属性被访问时的行为


__setattr__(self,
name, value)


定义当一个属性被设置时的行为


__delattr__(self,
name)


定义当一个属性被删除时的行为


__dir__(self)


定义当 dir() 被调用时的行为


__get__(self,
instance, owner)


定义当描述符的值被取得时的行为


__set__(self,
instance, value)


定义当描述符的值被改变时的行为


__delete__(self,
instance)


定义当描述符的值被删除时的行为

 
比较操作符


__lt__(self,
other)


定义小于号的行为:x < y 调用 x.__lt__(y)


__le__(self,
other)


定义小于等于号的行为:x <= y 调用 x.__le__(y)


__eq__(self,
other)


定义等于号的行为:x == y 调用 x.__eq__(y)


__ne__(self,
other)


定义不等号的行为:x != y 调用 x.__ne__(y)


__gt__(self,
other)


定义大于号的行为:x > y 调用 x.__gt__(y)


__ge__(self,
other)


定义大于等于号的行为:x >= y 调用 x.__ge__(y)

 
算数运算符


__add__(self,
other)


定义加法的行为:+


__sub__(self,
other)


定义减法的行为:-


__mul__(self,
other)


定义乘法的行为:*


__truediv__(self,
other)


定义真除法的行为:/


__floordiv__(self,
other)


定义整数除法的行为://


__mod__(self,
other)


定义取模算法的行为:%


__divmod__(self,
other)


定义当被 divmod() 调用时的行为


__pow__(self,
other[, modulo])


定义当被 power() 调用或 ** 运算时的行为


__lshift__(self,
other)


定义按位左移位的行为:<<


__rshift__(self,
other)


定义按位右移位的行为:>>


__and__(self,
other)


定义按位与操作的行为:&


__xor__(self,
other)


定义按位异或操作的行为:^


__or__(self,
other)


定义按位或操作的行为:|

 
反运算


__radd__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rsub__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rmul__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rtruediv__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rfloordiv__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rmod__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rdivmod__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rpow__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rlshift__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rrshift__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rand__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__rxor__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)


__ror__(self,
other)


(与上方相同,当左操作数不支持相应的操作时被调用)

 
增量赋值运算


__iadd__(self,
other)


定义赋值加法的行为:+=


__isub__(self,
other)


定义赋值减法的行为:-=


__imul__(self,
other)


定义赋值乘法的行为:*=


__itruediv__(self,
other)


定义赋值真除法的行为:/=


__ifloordiv__(self,
other)


定义赋值整数除法的行为://=


__imod__(self,
other)


定义赋值取模算法的行为:%=


__ipow__(self,
other[, modulo])


定义赋值幂运算的行为:**=


__ilshift__(self,
other)


定义赋值按位左移位的行为:<<=


__irshift__(self,
other)


定义赋值按位右移位的行为:>>=


__iand__(self,
other)


定义赋值按位与操作的行为:&=


__ixor__(self,
other)


定义赋值按位异或操作的行为:^=


__ior__(self,
other)


定义赋值按位或操作的行为:|=

 
一元操作符


__pos__(self)


定义正号的行为:+x


__neg__(self)


定义负号的行为:-x


__abs__(self)


定义当被 abs() 调用时的行为


__invert__(self)


定义按位求反的行为:~x

 
类型转换


__complex__(self)


定义当被 complex() 调用时的行为(需要返回恰当的值)


__int__(self)


定义当被 int() 调用时的行为(需要返回恰当的值)


__float__(self)


定义当被 float() 调用时的行为(需要返回恰当的值)


__round__(self[,
n])


定义当被 round() 调用时的行为(需要返回恰当的值)


__index__(self)


1.
当对象是被应用在切片表达式中时,实现整形强制转换
2. 如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 __index__
3. 如果 __index__ 被定义,则 __int__
也需要被定义,且返回相同的值

 
上下文管理(with 语句)


__enter__(self)


1.
定义当使用
with 语句时的初始化行为
2. __enter__ 的返回值被 with 语句的目标或者 as 后的名字绑定


__exit__(self,
exc_type, exc_value, traceback)


1.
定义当一个代码块被执行或者终止后上下文管理器应该做什么
2. 一般被用来处理异常,清除工作或者做一些代码块执行完毕之后的日常工作

 
容器类型


__len__(self)


定义当被 len() 调用时的行为(返回容器中元素的个数)


__getitem__(self,
key)


定义获取容器中指定元素的行为,相当于 self[key]


__setitem__(self,
key, value)


定义设置容器中指定元素的行为,相当于 self[key] = value


__delitem__(self,
key)


定义删除容器中指定元素的行为,相当于 del self[key]


__iter__(self)


定义当迭代容器中的元素的行为


__reversed__(self)


定义当被 reversed() 调用时的行为


__contains__(self,
item)


定义当使用成员测试运算符(in 或 not in)时的行为

例题:

#定义一个单词类继承于str,重写比较操作符当两个Word类比较时根据长度来比较,如果有空格根据空格前的长度来比较
class Word(str):
    def __init__(self,arg=‘‘):
        if isinstance(arg,str):
            if ‘ ‘in arg:
                arg=arg.split()[0]
            self.len=len(arg)
        else:
            print(‘参数错误‘)
    def __lt__(self,other):
        if self.len<other.len:
            return True
        else:
            False
    def __le__(self,other):

        if self.len<=other.len:
            return True
        else:
            return False
    def __eq__(self,other):
        if self.len==other.len:
            return True
        else:
            return False
    def __ne__(self,other):
        if self.len==other.len:
            return True
        else:
            return False
    def __gt__(self,other):
        if self.len>other.len:
            return True
        else:
            return False

    def __gt__(self,other):
        if self.len>=other.len:
            return True
        else:
            return False

方法二:

class Word(str):
    def __new__(cls,arg=‘‘):
        if isinstance(arg,str):
            if ‘ ‘ in arg:
                #arg=arg[:arg.index(‘‘)]
                arg=len(arg.split(‘ ‘)[0])
            else:
                arg=len(arg)
        else:
            print(‘输入错误‘)

        return str.__new__(cls,arg)
#定义一个类实现摄氏度到华氏度的转换

class CtoF(float):
    def __new__(cls,C):
        return float.__new__(cls,C*1.8+32)
#定义一个类支持字符串的相减炒作A-B中去除所有B的字符串
方法一
class Nstr(str):
    def __sub__(self,other):
        string=‘‘
        if isinstance(self,str) and isinstance(other,str):
            if other in self:
                str_list=self.split(other)
                for each in str_list:
                    string +=each
        return string
方法二:
class Nstr(str):
    def __sub__(self, other):
        return self.replace(other, ‘‘)

原文地址:https://www.cnblogs.com/PythonFCG/p/8428105.html

时间: 2024-08-02 03:02:37

Python3 魔法方法:算数运算的相关文章

Python3 魔法方法:属性访问

1.与属性访问有关的魔法方法 __getattr__(self,name) 定义当用户试图获取某一不存在的属性时的行为 __getattribute__(self,name) 定义当该类属性被访问时的行为 __setattr__(self,name,value) 定义一个属性被设置时的行为 __delattr__(self,name) 定义一个属性被删除时的行为 注意: def __setattr__(self, name, value): self.name = value + 1 #此代码试

Python3 魔法方法:定制序列

1.基于序列的三大容器 分别是 列表.元组.字符串 2.协议 python中的协议更像是一种指南,例如鸭子类型,一只鸟像鸭子一样走,像鸭子一样叫,像鸭子一样游然后这只鸟就可以叫做鸭子 3.容器类型的协议 如果希望定制的容器是不可变的,那么只需要定义__len__ 和__getitem__ 方法 如果希望定制的容器是可变的,那么还需要定义 __setitem__ 和__delitem__方法 4.魔法方法 _len__(self) 定义当被 len() 调用时的行为(返回容器中元素的个数) __g

Python3 魔法方法:迭代器

0.什么是迭代器 迭代器不是容器,而是实现了__next__方法的对象(用于遍历容器中的数据) 在python原生支持的数据结构中set(集合)是仅支持迭代器访问的,不支持下标(index)访问 1.相关的BIF iter() 将一个可迭代对象转换成一个迭代器 next() 访问迭代器中的下一个变量,如果迭代器没有变量了,则返回StopIteration异常 2.魔法方法 __iter__(self) 返回迭代器本身 __next__(self) 决定迭代的方法 3.例题: 用while语句实现

python魔法方法-反射运算和增量运算

反射运算 什么是反射运算符,其实就是反转了两个对象,下面先看一个普通运行符的实现: class Foo(object): def __init__(self, x): self.x = x def __add__(self, other): return 'Foo:%s + %s' % (self.x, other.x) class Boo(object): def __init__(self, x): self.x = x def __add__(self, other): return 'B

python3 与dict相关的魔法方法。使用于二叉搜索树的类中

Python的魔术方法一般以__methodname__的形式命名,如:__init__(构造方法), __getitem__. __setitem__(subscriptable所需method), __delitem__(del obj[key]所需method), __len__(len(…)所需method)等. 在Python中,如果我们想实现创建类似于序列和映射的类,可以通过重写魔法方法__getitem__.__setitem__.__delitem__.__len__方法去模拟.

python魔法方法详解

文章来源:http://blog.csdn.net/koko66/article/details/42709279 据说,Python 的对象天生拥有一些神奇的方法,它们总被双下划线所包围,他们是面向对象的 Python 的一切. 他们是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,你可以定义自己想要的行为,而这一切都是自动发生的. Python 的魔术方法非常强大,然而随之而来的则是责任.了解正确的方法去使

知识点:Python 魔法方法详解

据说,Python 的对象天生拥有一些神奇的方法,它们总被双下划线所包围,他们是面向对象的 Python 的一切. 他们是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,你可以定义自己想要的行为,而这一切都是自动发生的. Python 的魔术方法非常强大,然而随之而来的则是责任.了解正确的方法去使用非常重要! 魔法方法 含义 基本的魔法方法 __new__(cls[, ...]) 1. __new__ 是在一个

python魔法方法-属性转换和类的表示

类型转换魔法 类型转换魔法其实就是实现了str.int等工厂函数的结果,通常这些函数还有类型转换的功能,下面是一些相关的魔法方法: __int__(self) 转换成整型,对应int函数. __long__(self) 转换成长整型,对应long函数. __float__(self) 转换成浮点型,对应float函数. __complex__(self) 转换成 复数型,对应complex函数. __oct__(self) 转换成八进制,对应oct函数. __hex__(self) 转换成十六进

基本的魔法方法__ __

基本的魔法方法 __new__(cls[, ...])                                      1. __new__ 是在一个对象实例化的时候所调用的第一个方法                                                                2. 它的第一个参数是这个类,其他的参数是用来直接传递给 __init__ 方法