Reputation: 2187
Not sure how to quite phrase it, but here's the deal. I have a script where every variable is defined globally, but later I want to convert the script into a class for better encapsulation.
However, all the variables I used in the script needs to be converted into object variables. I would have changed something like
x = 5
into
self.x = 5
And after doing that all the functions in the script needs to be turned into methods of the class, however, most of the methods are mathematical formulas, and refactoring something as clean as
z = x ** y + x
into
z = self.x ** self.y + self.x
really hurts readability.
So as a solution to this I've been typing these really awkward re-naming at the beginning of the methods:
def method(self, ...):
x = self.x
y = self.y
...
It makes the formulas readable but typing all that re-naming is really painful, is there a more elegant way of doing this?
Upvotes: 1
Views: 1612
Reputation: 3301
self
is only a suggested name. I would encourage you to use it, but in some cases it is better to shorten it.
class A:
x = None
y = None
def calculate_z(s):
return s.x ** s.y + s.x
foo = A()
foo.x = 4
foo.y = 2
foo.calculate_z() # 20
Fun fact: you could even use unicode characters, like ® (in Python 3, that is).
def calculate_z(®):
return ®.x ** ®.y + ®.x
Upvotes: 7
Reputation: 133849
Well, there could be some other solutions, but they're all ugly hacks at most. You can make the code possibly less awkward by using multiple assignment though:
x, y = self.x, self.y
In addition x
and y
are faster to use in CPython than self.x
and self.y
, because the latter ones would need a costly attribute lookup for every use.
Upvotes: 0