【问题标题】:Custom function throws exception自定义函数抛出异常
【发布时间】:2020-08-03 02:50:09
【问题描述】:

所以我最近一直在使用列表,我正在尝试让一个特殊的类工作,所以我编写了一个 for 循环来测试基本功能,但它只是给了我这个回溯:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\nice code\v2.py", line 13, in <module>
    if Lenlist == len.lenList(len.listLen(List=len.list(list=List().list()))): print(Lenlist);
  File "C:\Users\User\Desktop\nice code\v2.py", line 3, in lenList
    def lenList(self, list=list): return len(list);
TypeError: 'List' object is not callable

这里是你的来源:

class List:
  List = list('list');
  def lenList(self, list=list): return len(list);
  def listLen(self, List=len): return list(List);
  def lenlist(self, len=list): return self.lenList(list=len);
  def list(self, list=list): return self.List;
  def listlen(self, len=len): return self.list(list=len);
len = List();
Lenlist = 0;
for Len in len.listLen(List=len.list(list=List().list())):
  if Len in list(len.listLen(List=len.list(list=Len))):
    Lenlist += list(len.listLen(List=len.list(list=Len))).count(Len);
    if Lenlist == len.lenList(len.listLen(List=len.list(list=List().list()))): print(Lenlist);

我期望它打印 List.List 的长度。我已经尝试用关键字替换所有位置参数。

【问题讨论】:

  • len = List() 隐藏内置函数。
  • 只是想在此处留下此评论,因为... 哇!lenlistception。可能口译员也惊讶于你使用了多少lenlistlen`,这让他有点害怕
  • 您可能需要考虑从list 派生您的课程。 docs.python.org/3/tutorial/classes.html#inheritance

标签: python python-3.x list oop


【解决方案1】:

这里有一些你需要遵循的关键说明

  1. 始终尽量避免覆盖 python 关键字或预定义函数(例如:len)

  2. 类中不能有与类名同名的变量名

我看到的第一个问题是你在 lenList 中覆盖了 len 你不会得到你想要的输出 我在您的代码中发现的第二个问题是 lenList 函数试图返回 len(list) list 是一个 python 预定义的类,所以 len 找不到任何东西

我稍微更改了您的代码,现在打印 4

class List:
  List1 = list('list');
  def lenList(self, list=list): return len(self.List1);
  def listLen(self, List=len): return list(self.List1);
  def lenlist(self, len=list): return self.lenList(list=len);
  def list(self, list=list): return self.List1;
  def listlen(self, len=len): return self.list(list=len);
len1 = List();
Lenlist = 0;

for Len in len1.listLen(List=len1.list(list=List().list())):
  if Len in list(len1.listLen(List=len1.list(list=Len))):
    Lenlist += list(len1.listLen(List=len1.list(list=Len))).count(Len);
    if Lenlist == len1.lenList(len1.listLen(List=len1.list(list=List().list()))): print(Lenlist);

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 2021-12-22
    相关资源
    最近更新 更多