python - 类函数在 Python 中找不到位置参数自身
问题描述
我在 Python 中创建了一个链表类,当调用我定义的 size 函数时,我收到以下错误:
TypeError: get_next() missing 1 required positional argument: 'self'
我尝试调用我定义的另一个函数,该函数也使用该get_next()
函数并且它没有产生错误。下面是类定义以及测试代码。
LinkedLists.py
:
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList(object):
def __init__(self, head = Node):
self.head = head
def insert(self, data):
new_node = Node(data)
new_node.set_next(self.head)
self.head = new_node
def size(self):
current = self.head
count = 0
while current:
count += 1
current = current.get_next()
return count
def search(self, data):
current = self.head
found = False
while current:
if current.get_data() == data:
found = True
else:
current = current.get_next()
if current is None:
raise ValueError("Data not in list")
return current
def delete(self, data):
current = self.head
previous = None
found = False
while current and found is False:
if current.get_data() == data:
found = True
else:
previous = current
current = current.get_next()
if current is None:
raise ValueError("Data not in list")
if previous is None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
def insert_at(self, data, location):
new_node = Node(data)
current = self.head
found = False
while current and found is False:
if current.get_data() == data:
found = True
else:
current = current.get_next()
if current is None:
raise ValueError("Data not in list")
new_node.set_next(current.get_next())
current.set_next(new_node)
LinkedListsTest.py
:
from LinkedLists import *
List = LinkedList()
List.insert(5)
List.insert(6)
List.insert(8)
List.delete(6)
print(List.size())
错误的完整追溯:
Traceback (most recent call last):
File "LinkedListsTest.py", line 10, in <module>
print(List.size())
File ".../LinkedLists.py", line 31, in size
current = current.get_next()
TypeError: get_next() missing 1 required positional argument: 'self'
解决方案
您设置self.head
为Node
class,而不是实例:
def __init__(self, head = Node):
self.head = head
注意Node
那里的参考。Node.get_next()
调用未绑定的方法,没有self
传入。
但是,不要设置head=Node()
为默认值;默认值在函数定义时设置一次,可变的默认值会导致您出现问题,因为您的LinkedList
类的所有实例都将共享一个实例。请参阅“Least Astonishment”和可变默认参数。
使用类似的哨兵None
来检测您是否需要创建默认值:
def __init__(self, head=None):
if head is None:
# create an empty default
head = Node()
self.head = head
通过此更正,您的测试打印3
.
推荐阅读
- mercurial - hg notify 在推送时给出“中断”
- php - 我使用哪个 API 来获取物品尺寸并从 ebay 订单的地址发货
- php - 使用 PHP 和 jQuery 从 MySQL 获取数据并显示在与用户 ID 匹配的 HTML 表中
- arrays - 用 replaceSubrange 修改 ArraySlice
- batch-file - 如何修复嵌套在 if 语句中的 Echo 命令
- c++ - 将模板化对象存储在向量中(存储类
, 班级 在单个向量中) - php - 如何从 Sabre API 获取酒店价格和重定向 url
- safari - Safari 12 在重定向 302 的情况下不缓存大资产,如果直接添加到页面中它可以正常工作吗?
- .net - 从 Postman 将用户添加到 Keyclock
- android - Android从FrameLayout获取孩子