Common errors for beginners related to self in Python is:
NameError: name 'self' is not defined
The keyword self is a special one and can only be used inside class methods where is defined as a parameter. Keyword self should be used only in class methods scope otherwise you will may get one of the errors above.
Example for incorrect usage:
self.me = "me"
11
class myclass:
def __init__(self):
name = 'name'
this code will cause error:
NameError: name 'self' is not defined
This is correct way to use self:
class myclass:
name = ''
def __init__(self):
self.name = 'name'
In general for self and python you can think in this way:
- It can be used for:
- When you define an instance method
- Referencing a class or instance attribute
Use self to refer to instance variables and methods from other instance methods.