self

What is the difference between class and instance variables?

What is the difference between class and instance variables? Question: What is the difference between class and instance variables in Python? class Complex: a = 1 and class Complex: def __init__(self): self.a = 1 Using the call: x = Complex().a in both cases assigns x to 1. A more in-depth answer about __init__() and self …

Total answers: 2

When do you use 'self' in Python?

When do you use 'self' in Python? Question: Are you supposed to use self when referencing a member function in Python (within the same module)? More generally, I was wondering when it is required to use self, not just for methods but for variables as well. Asked By: Dark Templar || Source Answers: For instance …

Total answers: 4

Is there a generic way for a function to reference itself?

Is there a generic way for a function to reference itself? Question: I can access a python function’s attribute inside of function itself by below code: def aa(): print aa.__name__ print aa.__hash__ # other simliar However, if above aa() function is a template for write other code, say bb(), I have to write: def bb(): …

Total answers: 4

What is the `self` parameter in class methods?

What is the purpose of the `self` parameter? Why is it needed? Question: Consider this example: class MyClass: def func(self, name): self.name = name I know that self refers to the specific instance of MyClass. But why must func explicitly include self as a parameter? Why do we need to use self in the method’s …

Total answers: 26

How to avoid explicit 'self' in Python?

How to avoid explicit 'self' in Python? Question: I have been learning Python by following some pygame tutorials. Therein I found extensive use of the keyword self, and coming from a primarily Java background, I find that I keep forgetting to type self. For example, instead of self.rect.centerx I would type rect.centerx, because, to me, …

Total answers: 11

Python decorators in classes

Python decorators in classes Question: Can one write something like: class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass This fails: self in @self is unknown I also tried: @Test._decorator(self) which also fails: Test unknown I would like to temporarily change some instance variables in the decorator and then run the decorated method, before …

Total answers: 14

Why do you need explicitly have the "self" argument in a Python method?

Why do you need explicitly have the "self" argument in a Python method? Question: When defining a method on a class in Python, it looks something like this: class MyClass(object): def __init__(self, x, y): self.x = x self.y = y But in some other languages, such as C#, you have a reference to the object …

Total answers: 10