鱼C论坛

 找回密码
 立即注册
查看: 1072|回复: 2

第43讲第五题 加了个__new__方法报错

[复制链接]
发表于 2018-6-4 19:55:32 | 显示全部楼层 |阅读模式

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

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

x
  1.         
  2. class C:
  3.         @staticmethod  # 该修饰符表示 static() 是静态方法
  4.         def static(arg1, arg2, arg3):
  5.                 print(arg1, arg2, arg3, arg1 + arg2 + arg3)

  6.         def nostatic(self):
  7.                 print("I'm the f**king normal method!")
复制代码


上面的代码,在实例化调用方法的时候时候都没问题,然后我就在类里加了两行:
  1.         def __new__(cls):
  2.             print("Create a new class.")
  3.         def __init__(self):
  4.             print("Init a new class.")
复制代码


在实例化的时候就报错了,不太明白到底是怎么回事
>>> c1 =C()
Create a new class.
>>> c1.nostatic
Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    c1.nostatic
AttributeError: 'NoneType' object has no attribute 'nostatic'
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-6-4 20:57:41 | 显示全部楼层
__new__方法里面还要返回self
  1. def __new__(self):
  2.     # do your things
  3.     return self
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-6-5 10:01:43 | 显示全部楼层
hi 原因如下:改写魔法方法 __new__()后,并未给出返回值

  1.         
  2. class C:

  3.         def __new__(cls):
  4.             print("Create a new class.")
  5.             return super().__new__(cls) #此处补充代码

  6.         def __init__(self):
  7.             print("Init a new class.")

  8.    
  9.         @staticmethod  # 该修饰符表示 static() 是静态方法
  10.         def static(arg1, arg2, arg3):
  11.                 print(arg1, arg2, arg3, arg1 + arg2 + arg3)

  12.         def nostatic(self):
  13.                 print("I'm the f**king normal method!")
复制代码


>>> c = C()
Create a new class.
Init a new class.
>>> c.static(1,2,3)
1 2 3 6
>>> c.nostatic()
I'm the f**king normal method!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-12-30 16:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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