-1

I'm new to python actually and I have a func that will add and sort, so I wanted to print the sorted list table but i'm getting an error

Traceback (most recent call last):
File "source_file.py", line 12, in <module>
App.addsort()
self.mytable.append(['Evans', '4', '2:23.717'])
NameError: name 'self' is not defined

This is the code - what am I doing wrong?

class App: 
    def __init__(self):
        self.mytable = [
        ('Charlie', '3', '2:23.169'),
        ('Dan', '5', '2:24.316'),
        ('Bill', '2', '2:23.123'),
        ('Alan', '1', '2:22.213'),
        ]
        self.sorted = sorted(self.mytable, key=operator.itemgetter(2))

    def addsort():
        self.mytable.append(['Evans', '4', '2:23.717'])
        print(self.sorted)

App.addsort()
user7716943
  • 485
  • 5
  • 15
  • You're missing the `self` as a parameter in the function. All the class functions must have `self` as the first parameter. Have a look at https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self – Keyur Potdar Mar 10 '18 at 07:24
  • maybe have a look at https://docs.python.org/3/tutorial/classes.html#a-first-look-at-classes – avigil Mar 10 '18 at 07:33
  • Whoever has downvoted thanks instead of rather being helpful and tell what I did wrong as I am new to python. nice job. – user7716943 Mar 10 '18 at 07:37

1 Answers1

2

Your method has to accept self as default parameter. change addsort method signature as below.

Adding self as parameter makes the method available for all the objects/instances of the class.

obj = App()
obj.addsort()


def addsort(self):
        self.mytable.append(['Evans', '4', '2:23.717'])
        print(self.sorted)

If you don't want addsort to be called/used by an instance, make it a class method and make sure it is not dependent on any of the self parameters.

Prakash Palnati
  • 3,231
  • 22
  • 35