See All Titles |
![]() ![]() EncapsulationAll Python attributes (variables and methods) are public. Even though you cannot have private attributes in Python, you can use the following two agreements:
We cannot say that Python supports private attributes because it is still possible to have access to the attributes if you know the class and attributes names. For example, in a class called C, the attribute self.__attr becomes self._C__attr, when exported from the class. Hence, you can access this attribute by referencing it as _C__attr. >>> class Number: …def __init__(self, value): … self._n = value … self.__n = value …def __repr__(self): … return '%s(%s)'% (self.__class__.__name__, self._n) …def add(self, value): … self._n = self._n + value …def incr(self): … self._n = self._n + 1 … Based on the previous class, we will have some interactive examples next. >>> a = Number(20) >>> a Number(20) >>> a.add(4) >>> a Number(24) >>> a.incr() >>> a Number(25) >>> a._n 25 >>> a._n = 30 >>> a Number(30) >>> a._Number__n 20 The important thing to remember is that nothing in Python is private (unless it is hidden within a C extension type). To demonstrate that you can use default arguments to help storing the environment variables in a variable from the class namespace, the next example initializes the value of the variable n by using a default argument. The value of n is assigned at the time of defining the function and is stored at the class namespace. >>> v = 10 >>> class C: …def storen(self, n=v): … return n … >>> objA = C() >>> objA.storen() 10 >>> v = 20 >>> objB = C() >>> objB.storen() 10 >>> n = 30 >>> objC = C() >>> objC.storen() 10 Note that the value of n remains constant for all instances of the class C. The following example shows that it is possible to manipulate the internal attributes of an object by directly accessing the members of a class. >>> class fun: …def __init__(self): … self.total = None … >>> a = fun() >>> b = fun() >>> a.total = 2 >>> b.total = 3 >>> print a, b 2 3 In this next example, we hide the a() method definition by preceding it with two underscores. Note that if you later need to access this method (and you don't want to rename it), you must create a reference to the method, as shown in the following example. >>> class C: …def __a(self): … print "ni!" …b = __a … >>> a = C() >>> a.b() ni!
|
Index terms contained in this sectionaccessingprivate attributes 2nd attributes objects changing private accessing 2nd changing object attributes class namespaces 2nd editing object attributes encapsulation mangling name manipulating object attributes modifying object attributes name mangling namespaces class 2nd object-oriented programming (OOP) encapsulation objects changing attributes private attributes accessing 2nd programming object-oriented (OOP) encapsulation |
© 2002, O'Reilly & Associates, Inc. |