鱼C论坛

 找回密码
 立即注册
查看: 927|回复: 3

[已解决]关于重写工厂函数的魔法方法

[复制链接]
发表于 2018-4-15 01:39:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我知道super()函数是用来调用基类的方法,为了实现改写加法为实际减法的过程中试着用了一下这个函数
class Try_int(int):
        def __add__(self, other):
                return super().__sub__(self, other)
为什么调用起来会报错,需要把代码改成以下才能实现
class Try_int(int):
        def __add__(self, other):
                return super().__sub__(other)
为什么不能带self
求大神帮忙解答!!
最佳答案
2018-4-15 07:56:29
hi 原因如下

分析一. 根据帮助手册 #help(super)
Typical use to call a cooperative superclass method:
|  class C(B):
|      def meth(self, arg):
|          super().meth(arg)
This works for class methods too:
|  class C(B):
|      @classmethod
|      def cmeth(cls, arg):
|          super().cmeth(arg)
super()函数自带self的

分析二. 根据报错提示也可以看到
    return super().__sub__(self, other)
TypeError: expected 1 arguments, got 2 #期待一个参数,但给了两个,self是多余的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

头像被屏蔽
发表于 2018-4-15 01:44:02 | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-4-15 07:40:30 | 显示全部楼层
原来的super里就自带self了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 2 反对 0

使用道具 举报

发表于 2018-4-15 07:56:29 | 显示全部楼层    本楼为最佳答案   
hi 原因如下

分析一. 根据帮助手册 #help(super)
Typical use to call a cooperative superclass method:
|  class C(B):
|      def meth(self, arg):
|          super().meth(arg)
This works for class methods too:
|  class C(B):
|      @classmethod
|      def cmeth(cls, arg):
|          super().cmeth(arg)
super()函数自带self的

分析二. 根据报错提示也可以看到
    return super().__sub__(self, other)
TypeError: expected 1 arguments, got 2 #期待一个参数,但给了两个,self是多余的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-17 14:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表