鱼C论坛

 找回密码
 立即注册
查看: 2029|回复: 5

[已解决]python 类 报错

[复制链接]
发表于 2022-7-13 18:05:19 | 显示全部楼层 |阅读模式

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

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

x
以下三段代码 ,只有一段报错。
  1. class A(str):
  2.     def __new__(ls,string):
  3.         string = string.upper()
  4.         return str.__new__(ls,string)


  5. a = A('l love FishC.com!')
  6. print(a)
复制代码
  1. class A(str):
  2.     def __new__(sss,string):
  3.         string = string.upper()
  4.         return str.__new__(sss,string)


  5. a = A('l love FishC.com!')
  6. print(a)
复制代码
  1. class A(str):
  2.     def __new__(ls,string):
  3.         string = string.upper()
  4.         return str.__new__(cls,string)


  5. a = A('l love FishC.com!')
  6. print(a)
复制代码
最后一段代码,报错如下
  1. NameError: name 'cls' is not defined
复制代码
最佳答案
2022-7-13 18:14:46
  1. class A(str):
  2.     def __new__(ls,string): #这里你在定义时形参的名字为 "ls",所以后面需使用 "ls" 作为变量名,并不存在 "ls" 这个变量!
  3.         string = string.upper()
  4.         return str.__new__(cls,string) #应该为 "ls"


  5. a = A('l love FishC.com!')
  6. print(a)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-7-13 18:08:53 | 显示全部楼层
本帖最后由 青出于蓝 于 2022-7-13 18:10 编辑

第4行,哪来的cls
  1. class A(str):
  2.     def __new__(ls,string):
  3.         string = string.upper()
  4.         return str.__new__(ls,string)


  5. a = A('l love FishC.com!')
  6. print(a)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-7-13 18:14:46 | 显示全部楼层    本楼为最佳答案   
  1. class A(str):
  2.     def __new__(ls,string): #这里你在定义时形参的名字为 "ls",所以后面需使用 "ls" 作为变量名,并不存在 "ls" 这个变量!
  3.         string = string.upper()
  4.         return str.__new__(cls,string) #应该为 "ls"


  5. a = A('l love FishC.com!')
  6. print(a)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-7-13 18:57:27 | 显示全部楼层

这在小甲鱼那一颗讲的,我回去复习一下。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-7-13 18:59:18 | 显示全部楼层

还有是不是每一个类的形参是不一样的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-7-13 20:13:45 | 显示全部楼层
shiyouroc 发表于 2022-7-13 18:59
还有是不是每一个类的形参是不一样的

这里的形参是指你在定义类中的方法,也就是函数时,在括号里填的参数,如:
  1. def __new__(ls,string):
复制代码

这里的 ls,string 就是形参,具体的你可以翻小甲鱼前面的关于函数的课堂笔记
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-28 02:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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