Python importing class attributes into method local namespace

前端 未结 3 1178
鱼传尺愫
鱼传尺愫 2021-02-14 00:57

I have been wondering for a while if there is easier way to assign class attributes to method local namespace. For example, in dosomething method, I explicitly make

相关标签:
3条回答
  • 2021-02-14 01:05

    Q. Is there any way to do this more compact way?

    1. If the variables are read-only, it would be reasonably Pythonic to factor-out a multi-variable accessor method:

    class Test:
    
        def __init__(self):
            self.a = 10
            self.b = 20
            self.c = 30
    
        def _read_vars(self):
            return self.a, self.b, self.c
    
        def dosomething(self):
            a, b, c = self._read_vars()
            return a + b * c
    
        def dosomethingelse(self):
            a, b, c = self._read_vars()
            return a - b * c
    

    If the variables aren't read-only, it is best to stick with self.inst_var = value. That is the normal way to write Python code and is usually what most people expect.


    2. Once in a while you will see people abbreviate self with a shorter variable name. It is used when the readability benefits of decluttering outweigh the readability cost of using a non-standard variable name:

    def updatesomethings(s):
        s.a, s.b, s.c = s.a + s.c, s.b - s.a, s.c * s.b
    

    3. Another way to handle a very large number instance variable is to store them in a mutable container for ease of packing and unpacking:

    class Test:
    
        def __init__(self, a, b, c, d, e, f, g, h, i):
            self._vars = [a, b, c, d, e, f, g, h, i]
    
        def fancy_stuff(self):
            a, b, c, d, e, f, g, h, i = self._vars
            a += d * h - g
            b -= e * f - c
            g = a + b - i
            self._vars[:] = a, b, c, d, e, f, g, h, i
    

    4. There is also a dictionary manipulation approach that would work, but it has a code smell that most Pythonistas would avoid:

    def updatesomethings(self):
        a = 100
        b = 200
        c = 300
        vars(self).update(locals())
        del self.self
    
    0 讨论(0)
  • 2021-02-14 01:26

    I found another way:

    def dosomething(self):
        for key in ['a', 'b']:
           exec('{} = self.{}'.format(key, key))
    
        return(a + b)
    

    I don't know if this is dangerous or not. Would be great if someone can comment on this.

    0 讨论(0)
  • 2021-02-14 01:29

    You can easily solve this problem with a tradeoff, by storing the variables in a dictionary.

    data = {}
    copy_to_local_variables = ["a", "b", "c", "d"]
    for var_name in copy_to_local_variables:
        data[var_name] = getattr(self, var_name)
    

    (Though I am unable to understand why you need to copy class attributes to method local namespace)

    0 讨论(0)
提交回复
热议问题