[3-2] Python Advanced Access Restrictions

We can give an example of binding a lot of property, some property if you do not want to be accessible to the outside how to do?

Python control of property rights is achieved by property name,
external access if a property by the beginning of the double underscore (__), the property can not be.
Look at an example:

class Person(object):
    def __init__(self, name):
        self.name = name
        self._title = 'Mr'
        self.__job = 'Student'
p = Person('Bob')
print p.name
# => Bob
print p._title
# => Mr
print p.__job
# => Error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute '__job'

Visible only to double-underlined at the beginning of "__job" can not be directly accessed externally.

However, if a property to " __xxx__" define form, that it can be accessed outside of " __xxx__" the definition of property is called the Python class special attributes usually we have a lot of predefined special properties may be used, Do not use common property " __xxx__" definition.

To attribute a single leading underscore " _xxx" although it can be accessed externally, but, by convention, they should not be external access.



task:

Please add to the __init__ method Person class name and score parameters, and the score is bound to the __score properties to see whether the external access to.

CODE:

class Person(object):
    def __init__(self, name, score):
        self.name = name
        self.__score = score

p = Person('Bob', 59)

print p.name
try :
    print p.__score
except AttributeError:
    print 'attributeerror'

Here Insert Picture Description

Published 20 original articles · won praise 0 · Views 391

Guess you like

Origin blog.csdn.net/yipyuenkay/article/details/104496639