I. Access control for class attributes
Python class is really profound, so let's review the property's access control as the open (Fu) field (xi).
First _varname is accessible, __varname is not directly accessible (the principle is __varname becomes _classname__varname)
1>>>classA:2... _aa = 13...__BB= 24 ...5>>>6>>>7>>> C =A ()8>>>C._aa91Ten>>> c.__BB One Traceback (most recent): AFile"<stdin>", Line 1,inch<module> -ATTRIBUTEERROR:A instance has no attribute'__BB' ->>>C._A__BB the2 - >>>
Second, the built-in function:
Do not want to verbose directly on the code, comments to explain:
1 classPerson (object):2 def __init__(self,name):3Self.name =name4 def __str__(self):5 return "<class:person name:%s>"%Self.name6 def __repr__(self):7 return "<Name:%s>"%Self.name8 9Tom = Person ("Tom")TenPrint repr (Tom) One PrintTom
1 classPerson (object):2 def __init__(self,name,age):3Self.name =name4Self.age = Age5 def __str__(self):6 return "<class:person name:%s>"%Self.name7 def __repr__(self):8 return "<Name:%s>"%Self.name9 def __len__(self):Ten returnSelf.age OneTom = Person ("Tom", 20) A Printrepr (Tom) - PrintTom - PrintLen (Tom)
And of course there are many:
1 def __iter__(self):#overriding built-in iteration capabilities2RET =do_something ()3 returnret4 5 def __getitem__(self):#Add the following table to object function6 Pass7 8 def __getattr__(self):#to increase the processing of their own properties9 PassTen One def __call__(self):#Direct instances as function calls A Pass - """ - class A: the def __call__ (self): - print "OK" - a = a () - A () + >>> OK - """
Thirdly, @property method is attributed:
1 classStudent:2 def __init__(self,name):3Self.name =name4 @property5 defAge (self):6 returnSelf.age7 @age. Setter8 defAge (self,age):9Self.age = AgeTen One """ A A = Student ("Stu") - a.age = - A.age the >>> - """
The Python class's property access control and built-in function overrides enable advanced functionality and @property