简体   繁体   中英

How do I create an alias for a variable in Python?

Normal way:

class A:
    def __init__(self):
        self.a.b.c = 10

    def another_method(self):
        self.a.b.c = self.a.b.c * 10

Aliased approach:

class A:
    def __init__(self):
        self.a.b.c = 10         
        alias self.aliased = self.a.b.c  # Creates an alias 

    def another_method(self):
        self.aliased = self.aliased * 10  # Updates value of self.a.b.c

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.

The solution to this is to use getter and setter methods - fortunately Python has the property() builtin to hide the ugliness of this:

class A:
    def __init__(self):
        self.a.b.c = 10

    @property
    def aliased(self):
        return self.a.b.c

    @aliased.setter
    def aliased(self, value):
        self.a.b.c = value

    def another_method(self):
        self.aliased *= 10  # Updates value of self.a.b.c

Generally, deeply nested attributes like self.abc 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.

Python doesn't copy anything implicity, it only stores references so it will work no matter which environment you're 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's no copy.
alias = really_really_long_variable_name

alias.append('AIB')
print really_really_long_variable_name

You'll get ['AIB']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM