我想在函数中使用函数,但出现错误 我想获取上一个对象,当前对象和下一个对象,我如何定义任何人都可以帮助我? 其实我是编程新手 提前谢谢你
class DataHandler:
def previous_and_next(some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
return zip(prevs, items, nexts)
def current_obj(self):
print("The current object is : ",employee_list[0])
def next_obj(se):
property = previous_and_next(employee_list)
for previous, item, nxt in property:
print("Item is now", item, "next is", nxt, "previous is", previous)
employee_list = []
n = int(input("Enter number of Employee you want to add:"))
for i in range(n):
fname = input("Enter First name : ")
lname = input("Enter Last name : ")
emp_type = input("Enter Employee type : ")
details = [fname,lname,emp_type]
print(details)
employee_list.append(details)
obj = DataHandler()
obj.current_obj()
obj.next_obj()
我在以下位置收到错误: 属性 = previous_and_next(employee_list( 名称错误: 未定义名称"previous_and_next">
您的问题是您正在尝试访问属于类实例的方法。您需要使用self
:
def next_obj(self):
property = self.previous_and_next(employee_list)
for previous, item, nxt in property:
print("Item is now", item, "next is", nxt, "previous is", previous)
您还需要使previous_and_next
方法将self
作为参数,或使其成为staticmethod
:
def previous_and_next(self, some_iterable):
或
@staticmethod
def previous_and_next(some_iterable):
我不相信您的其余代码实际上会达到预期的结果,但这应该可以解决您遇到的错误。
好吧,你可以通过self
来定义函数。只需在所有函数中添加 self,然后您就可以使用:
def previous_and_next(self,some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
return zip(prevs, items, nexts)
属性 = self.previous_and_next(employee_list(