Answer the question
In order to leave comments, you need to log in
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)
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())
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question