what is the difference between name and _name?

luofeiyu elearn2014 at gmail.com
Wed Aug 20 07:41:11 EDT 2014


So in this example:
>> class Person(object):
>>       def __init__(self, name):
>>           self._name = name
>         [...]
>>       name = property(getName, setName, delName, "name property docs")
>
>
> (3) name is the public attribute that other classes or functions are
> permitted to use.
>
>
> problem 1:  there is no self.name =  something in the defination ,why i can get bob.name?
>
>
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")

 >>> bob=Person("dear bob")
 >>> bob._name  # there is a defination in class Person ,self._name = 
name ,when we initial it ,we can get bob._name
'dear bob'
 >>> bob.name  #there is no defination in class Person ,self.name=name 
,why we can get the value of bob.name?
fetch....
'dear bob'


problem 2: what is the meaning of

name = property(getName, setName, delName, "name property docs")    ?

why i can not write  _name = property(getName, setName, delName, "name property docs") ?


  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")

bob=Person("dear bob")

I got error from the codes:

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




More information about the Python-list mailing list