0

I want to use function inside function but I get error I want to get previous object,current object and next object how can I define that can anyone help me ? Actually I am new into the programming Thank you in advance

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()

I am getting error at : property = previous_and_next(employee_list) NameError: name 'previous_and_next' is not defined

Rin
  • 81
  • 1
  • 2
  • 11

2 Answers2

2

Your issue is that you are trying to access a method that belongs to an instance of a class. You need to use 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)

You also need to do make the previous_and_next method take self as an argument, or make it a staticmethod:

def previous_and_next(self, some_iterable):

or

@staticmethod
def previous_and_next(some_iterable):

I'm not convinced that the rest of your code will actually achieve the intended result, but this should fix that error you have.

PyPingu
  • 1,697
  • 1
  • 8
  • 21
  • While I use self it throws another error that :TypeError: previous_and_next() takes 1 positional argument but 2 were given @PyPingu – Rin Aug 06 '19 at 09:13
  • See my edit. Methods that belong to an instance of a class are always passed an argument (`self` - the name is by convention only) which is the instance. Read [this](https://medium.com/quick-code/understanding-self-in-python-a3704319e5f0). – PyPingu Aug 06 '19 at 09:14
1

Well you can define function by self. Just add self in all functions and then you can use:

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)

Property = self.previous_and_next(employee_list)