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
?
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.
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.
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.
NameError is raised when the identifier being accessed is not defined in the local or global scope.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With