Normal way:
JavaScript
x
7
1
class A:
2
def __init__(self):
3
self.a.b.c = 10
4
5
def another_method(self):
6
self.a.b.c = self.a.b.c * 10
7
Aliased approach:
JavaScript
1
8
1
class A:
2
def __init__(self):
3
self.a.b.c = 10
4
alias self.aliased = self.a.b.c # Creates an alias
5
6
def another_method(self):
7
self.aliased = self.aliased * 10 # Updates value of self.a.b.c
8
How does one accomplish aliasing in Python? The reason I want to do this is to reduce cluttering due to long variable names. It’s a multi threaded environment, so simply copying to a local variable will not work.
Advertisement
Answer
The solution to this is to use getter and setter methods – fortunately Python has the property()
builtin to hide the ugliness of this:
JavaScript
1
15
15
1
class A:
2
def __init__(self):
3
self.a.b.c = 10
4
5
@property
6
def aliased(self):
7
return self.a.b.c
8
9
@aliased.setter
10
def aliased(self, value):
11
self.a.b.c = value
12
13
def another_method(self):
14
self.aliased *= 10 # Updates value of self.a.b.c
15
Generally, deeply nested attributes like self.a.b.c
are a sign of bad design – you generally don’t want classes to have to know about objects that are 3 relationships away – it means that changes to a given item can cause problems throughout your code base. It’s a better idea to try and make each class deal with the classes around it, and no further.