what is the difference between name and _name?

luofeiyu elearn2014 at gmail.com
Fri Aug 22 02:37:08 EDT 2014


I fix a mistake in Steven D'Aprano interpretation.

class Person(object):
      def __init__(self, name):
          self._name = name
      def getName(self):
          print('fetch....')
          return self._name
      def setName(self, value):
          print('change...')
          self._name = value
      def delName(self):
          print('remove....')
          del self._name
      _name = property(getName, setName, delName, "name property docs")


x=Person("peter")

It can not initinalize.
   File "<stdin>", line 9, in setName
   File "<stdin>", line 8, in setName
RuntimeError: maximum recursion depth exceeded while calling a Python 
object.

Steven D'Aprano interpretation:

10 Python finds the property _name
20 Python retrieves the getter, getName
30 Python runs the getName() method
40 which looks up self._name
50 go to 10

the right interpretation according to the error message:


10 python call __init__ method. self._name = name
20 python call setName method,
          print('change...')
          self._name = value
30 from self._name = value ,python call call setName method again

then we get a recursion error.
>> why i can not write  _name = property(getName, setName, delName, "name
>> property docs") ?
> Because you will have infinite recursion.
>
> When you look up instance._name:
>
> 10 Python finds the property _name
> 20 Python retrieves the getter, getName
> 30 Python runs the getName() method
> 40 which looks up self._name
> 50 go to 10
>
> and you get a recursion error.
>
>
>




More information about the Python-list mailing list