Self Best Practices
Naming and Conventions
Consistent Self Usage
Always use self
as the first parameter in instance methods to maintain readability and follow Python conventions.
class GoodPractice:
def __init__(self, name):
self.name = name ## Correct way to use self
def display_name(self):
print(f"Name: {self.name}") ## Consistent self usage
Avoiding Common Mistakes
Immutable Self References
class AvoidThisMistake:
def __init__(self, value):
self.value = value
def modify_value(self, new_value):
## Correct: Modify instance attribute
self.value = new_value
def incorrect_modification(self, new_value):
## Incorrect: This does not modify the instance attribute
value = new_value
Self Best Practices Table
Practice |
Recommendation |
Example |
Attribute Access |
Always use self |
self.attribute |
Method Calls |
Use self to call methods |
self.method() |
Initialization |
Set attributes in __init__ |
self.name = name |
Avoid Global State |
Use instance attributes |
Prefer self.data over global variables |
Method Chaining with Self
class DataProcessor:
def __init__(self):
self.data = []
def add(self, item):
self.data.append(item)
return self ## Enable method chaining
def remove_duplicates(self):
self.data = list(set(self.data))
return self
Self in Inheritance
class Parent:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello from {self.name}")
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) ## Proper use of parent's __init__
self.age = age
def introduce(self):
print(f"{self.name} is {self.age} years old")
Visualization of Self Scope
graph TD
A[Instance Creation] --> B[Self References Instance]
B --> C{Method Calls}
C -->|Access Attributes| D[self.attribute]
C -->|Call Methods| E[self.method()]
Lightweight Self Usage
class OptimizedClass:
__slots__ = ['name', 'value'] ## Reduce memory overhead
def __init__(self, name, value):
self.name = name
self.value = value
Common Anti-Patterns to Avoid
- Modifying
self
outside of methods
- Creating unnecessary instance attributes
- Overusing complex inheritance
LabEx Recommendation
At LabEx, we emphasize clean, readable, and efficient use of self
to create robust Python class designs.
Advanced Self Techniques
Property Decorators
class SmartClass:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
@value.setter
def value(self, new_value):
if new_value > 0:
self._value = new_value