A
A
Alexey Babiev2018-12-17 21:48:31
Python
Alexey Babiev, 2018-12-17 21:48:31

What is the correct way to interact with Python 3+ class attributes?

class A:
    name = 'default'

a = A()
a.name = 'new'
print('Name =', a.name)

or
class A:
    __name__ = 'default'

    getName = lambda self: self.__name__

    def setName(self, name):
        self.__name__ = name

a = A()
a.setName('new')
print('Name =', a.getName())

As for me, the first option is shorter and more concise, and the second one is more kosher.
But still, which is better?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-12-17
@axsmak

First, lambda assignment is an antipattern. Secondly, the first option is more idiomatic. Thirdly, if it is necessary to implement the logic of accessing attributes, then it would be more correct to use properties :

class A:
    def __init__(self, name='default'):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value


a = A()
print(a.name)
a.name = 'test'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question