Advanced object-oriented (2)

_ _ Slots _ _ Magic

We are talking about this, I do not know whether you have realized, Python is a dynamic language . Typically, dynamic languages allow new property or method we bind to the object in the running, of course, can unbind the properties and methods have been bound. But if we need to define custom type of object can only bind certain attributes can be defined by class _ _ slots _ _ variable to be defined. Note that _ _ slots _ _ limited only to the current class of objects into effect, sub-class does not play any role.

 

Static methods and class methods

@classmethod: Get Class itself (cls) attributes, and can be changed.
a classmethod modifiers need not instantiate the corresponding function, no self parameters, but the first parameter is a required parameter itself cls class can be invoked attribute class, the class methods, and other objects instantiated

                                                                    

 

 

After the subclass inherits the parent class, you can give a new version of the realization of the existing parent class, this action is called method overrides (override). By rewriting method we can make the same behavior of the parent class has a different version in a subclass to achieve, when we call passes this subclass rewritten, different subclasses of objects exhibit different behavior, this is the polymorphism (poly-morphism).

Example 1: 

Input three numbers (private), and find three numbers,
try to change where the two figures
"" "
class Number The (Object):
DEF __init __ (Self, num1, num2, num3):
self._num1 = num1
Self .__ num2 num2 =
Self num3 .__ = num3

@Property
DEF num1 (Self):
Print (self._num1)

@ num1.setter
DEF (Self, NUM):
self._num1 NUM =

DEF the SUM (Self):
Print (Self self._num1 + .__ num2 + self .__ num3)


number = Number(1,2,3)
# number.num1 = 10000
number.num1 = 1000
number.SUM()

Example 2:

                                                                                

 

                                                                       

                                             

列表生成式 :
a=(x for x in range(100) if x %2 == 0
print(a)
优点:计算速度快,以为一次性已经全部加载到内存中了,适合数据量不是太大的情况
缺点:占用内存
生成器 genter = (
a=(x for x in range(100) if x %2 == 0
优点:节约内存空间
缺点:计算速度慢,因为要生成

Guess you like

Origin www.cnblogs.com/yzm1020/p/11323267.html