class parent(object):__default = "parent"def __init__(self, name=None):self.default = name or self.__default
@propertydef default(self):return self.__default
@default.setterdef default(self, value):self.__default = value
class child(parent):__default = "child"
class BaseForm(StrAndUnicode):
def _get_errors(self):"Returns an ErrorDict for the data provided for the form"if self._errors is None:self.full_clean()return self._errors
errors = property(_get_errors)
class A(object):def __test(self):print "I'm a test method in class A"
def test(self):self.__test()
a = A()a.test()# a.__test() # This fails with an AttributeErrora._A__test() # Works! We can access the mangled name directly!
输出:
$ python test.pyI'm test method in class AI'm test method in class A
现在创建一个子类B并定制__test方法
class B(A):def __test(self):print "I'm test method in class B"
b = B()b.test()
class FalseCalculator(object):
def __init__(self, number):self.number = number
def __add__(self, number):return self.number - number
def __sub__(self, number):return self.number + number
number = FalseCalculator(20)print number + 10 # 10print number - 20 # 40
class A():here="abc"_here="_abc"__here="__abc"
aObject=A()print(aObject.here)print(aObject._here)# now if we try to print __here then it will fail because it's not public variable#print(aObject.__here)
# bar.py
from foo import *
print(dir()) # list of defined objects, contains 'var' but not '_var'print(var) # varprint(_var) # NameError: name '_var' is not defined
(Python) = (Java)_single_underscore_variable = Protected (Accessible to class and its subclasses)__double_underscore_variable = Private (Accessible to class itself only)no_underscore_variable = Public (Accessible anywhere)