[Level 3] Python Encapsulation.

There are two ways to implement property encapsulation.

[test1.py]
#!/bin/env python

class C(object):
#class C():
    y = 3
    z = 4

    def __init__(self):
        self.__x = 2
        self.z = 0
        self._z = 00
        self.__z = 000

    def getx(self):
        return self.__x

    def setx(self, val):
        print "x is read only"

    x = property(getx, setx)
#    x = property(getx)
#    x = property(lambda self: self.__x)

c=C()
print(c.x,c.y,c.z)
c.x=3
print(c.x,c.y,c.z)
print c.z
print c._z
print c.__z #AttributeError


[test2.py]
#!/bin/env python
#!/bin/env python
class B(object):
   def __init__(self):
       self.__x = None

   @property
   def x(self):
       """I'm the 'x' property."""
       return self.__x

   @x.setter
   def x(self, value):
       self.__x = value

   @x.deleter
   def x(self):
       del self.__x

b=B()
b.x=12
print(b.x)
print(b.__x) #AttributeError



Wish this helps.
regards,
Stanley Huang

Comments

Popular posts from this blog

[Level 1] Rar tool for Solaris.

[Level 2] iif in Python