Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: name 'self' is not defined

Why such structure

class A:     def __init__(self, a):         self.a = a      def p(self, b=self.a):         print b 

gives an error NameError: name 'self' is not defined?

like image 855
chriss Avatar asked Nov 26 '09 10:11

chriss


People also ask

How do I fix NameError self is not defined?

The “NameError: name 'self' is not defined” error is raised when you forget to specify “self” as a positional argument or when you use “self” in another argument in a list of arguments. You solve this error by making sure that all methods in a function that use “self” include “self” in their list of arguments.

How do I fix my NameError in python?

The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.

What is self in python function?

The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the '@' syntax to refer to instance attributes.

What causes NameError in python?

NameError is raised when the identifier being accessed is not defined in the local or global scope.


1 Answers

Default argument values are evaluated at function define-time, but self is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.

It's a common pattern to default an argument to None and add a test for that in code:

def p(self, b=None):     if b is None:         b = self.a     print b 

Update 2022: Python developers are now considering late-bound argument defaults for future Python versions.

like image 181
intgr Avatar answered Oct 05 '22 15:10

intgr