How to create an alias for a variable in Python?

The usual way

class A: __init__(): self.abc = 10 anotherMethod(): self.abc = self.abc * 10 

Alias ​​approach

 class A: __init__(): self.abc = 10 alias self.aliased = self.abc # Creates an alias anotherMethod(): self.aliased = self.aliased * 10 # Updates value of self.abc 

How to perform pseudonization in Python? The reason I want to do this is to reduce the amount of interference due to long variable names. This is a multi-threaded environment. , so just copying to a local variable will not work.

+7
source share
3 answers

The solution to this is to use the getter and setter methods - fortunately, Python has a built-in property() to hide the ugliness of this.

 class A: def __init__(): self.abc = 10 @property def aliased(self): return self.abc @aliased.setter def aliased(self, value): self.abc = value def anotherMethod(): self.aliased *= 10 # Updates value of self.abc 

As others have noted, this is usually a sign of poor design - you usually don’t want classes to know about objects that have three relationships - this means that changes to a given element can cause problems in the entire code base. It is a better idea to try to get each class to deal with the classes around it, and not further.

+18
source

You are confused. Python does not implicitly copy anything, it only stores links, so it will work no matter what environment you are in.

 # this creates a list and stores a *reference* to it: really_really_long_variable_name = [] # this creates another new reference to the *same list*. There no copy. alias = really_really_long_variable_name alias.append('AIB') print really_really_long_variable_name 

You will receive ['AIB']

+8
source

You can get the desired behavior using descriptors, but only for member variables.

+1
source

Source: https://habr.com/ru/post/918167/


All Articles