0

I am new to object-oriented programming in Python and have what seems to be a simple question and need some guidance.

If I have the following object myclass which is being initilized with self and a file path fname:

class myclass(object):
    def __init__(self, fname):
        self.fname = fname
        self.title = None
        self.geo_list = []

Everything seems to work.

a = myclass('a')

a has the three properties specified in __init__.

But If I add a line to check to make sure fname is not blank or None:

class myclass(object):
    def __init__(self, fname):
        self.fname = fname
        self.title = None
        self.geo_list = []

    if self.fname == '' or self.fname is None:
        raise AttributeError('Filename passed is blank.')

I get the NameError:

name 'self' is not defined
dubbbdan
  • 2,650
  • 1
  • 25
  • 43

1 Answers1

1

self is not a keyword in Python, it's just a plain variable name with no meaning in itself.

But there is a convention - which as far as I know is universally followed, and therefore which you should follow yourself - by which the first argument of every method in a Python class is called self. And this first argument is indeed a bit special, because whenever the method is called, the object itself (which is an instance of the class) is passed in as the first parameter - followed by all the other parameters that were explicitly given. So when you put a = myclass('a'), the __init__ method got called with 'a' as the second argument (which you called fname) and a itself as the first (which by convention is called self). [Obviously it's not quite like that because a isn't actually defined until the __init__ has returned, but that's I think a reasonable way of looking at it.]

So you can only access self inside a method, in which self should always be the first argument.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34
  • For some reason I didn't realize' inside a method' means inside a function with `self`. Thank you! – dubbbdan Apr 23 '19 at 14:24
  • 1
    They're are used interchangeably (incorrectly) but in Python's scope a method *is* a function, but resides within an object/class (and hence makes use of self, unless for example the method is static). – Nordle Apr 23 '19 at 14:36