1. The advantages of object-oriented thinking
Advantages: simplifies code, build a common template, scalability
Thought: class as a template, the template objects by instantiating an object, the object to do something, there is something of the abstract will be displayed using the code reflects
2. Three characteristics
Package (narrow): the attributes of the package, the package of the method
inherit
1. All sub-class has a parent class in addition to private content
2. Object by subclass - superclass method -... find properties they need
3.py3 default inherited object is new-style class, using c3 algorithm, print (type .mro ()) to determine the class name to view multiple inheritance order of succession
4.super (). Method, you can call the parent class method of the same name
class Base: def __init__(self): print('BASE') class A(Base): def __init__(self): super().__init__() print('A') class B(Base): def __init__(self): super().__init__() print('B') class C(A, B): def __init__(self): Super (). the __init__ () Print ( ' C ' ) C () Print (C.mro ()) # in accordance with the order of the algorithm, the order of succession determines a class
Polymorphism
3. Members
Property (__dict__ View)
Properties of the object
Class of property
Method (dir () View)
Common method
Class Methods: @classmethod
Static method: @staticmethod ordinary function in class
Property (Method camouflage properties)
Many methods are performed after obtaining a result, unlike a motion
@property # disguise property
.Setter # @ name of the method according to the incoming values, to change the properties of the return value
Private member
Variable or method can only be called internal, private property, private class method, the object of private property
self 与 cls
self parameter is the object itself, when the object is instantiated, the object is invoked when the memory address to self
cls parameter is the class itself
class the Person: local = ' earth ' # private class attributes __character__ = ' positive ' DEF the __init__ (Self, name, AD, HP, Character): the self.name = name self.ad = AD self.hp = HP # private object property . Self __character__ = Character # private class method DEF __local__ (CLS): Print (CLS. __character__ ) # class method @classmethod def Dict(cls): return cls.__dict__ # 静态方法 @staticmethod def Sum(n): return n + 2 # 属性Info @property def Info(self): return '{}-{}-{}'.format(self.name, self.ad, self.hp) # 修改属性Info @Info.setter def Info(self, values): if values < 100: self.ad = values print(Person.__character__) Print (Person.Dict ()) Print (Person.Sum (2 )) OBJ1 = the Person ( ' Lucy ' , 10, 50, ' active left ' ) Print (obj1.Info) obj1.Info = 99 Print (OBJ1. info)
4. The behavior of an object
Instantiate an object
1 .__ new__ way to create objects in memory to open up space
2. Perform the object initialization method __init__
Object invoke properties and methods of order
Looking priority in memory -> Object interior of the package -> Class -> parent
5. The relationship between class and class
Dependencies: low interdependence is a class when you need to perform an action, you need to attribute other methods to help complete the class, usually called by an object parameter
class Eat:
def handler(self, *args):
for i in args:
i.eat()
class Apple:
def eat(self):
print('吃苹果')
class Pear:
def eat(self):
print('吃梨')
obj = Eat()
obj1 = Apple()
obj2 = Pear()
obj.handler(obj1, obj2)
Relationship: the two things must be related to each other but in some special cases can be changed and replaced.
class Country:
def __init__(self, name):
self.name = name
self.pro_list = []
def add_pro(self, pro):
self.pro_list.append(pro)
def show_pro(self):
for i in self.pro_list:
print(i.name, i.cou)
class province:
def __init__(self, name, country):
self.name = name
self.cou = country
C1 = Country('火星国')
p1 = province('省1', C1.name)
p2 = province('省2', C1.name)
C1.add_pro(p1)
C1.add_pro(p2)
C1.show_pro()
Inheritance: non-private property is inherited parent class, self will look for ways to start the object properties, when there is no time to go looking for parent class
6. The interface class (abstract constraints)
Use interface class is a succession, inheritance can make a subclass of parent class has the code to prevent code duplication, you can also define an interface class, only define the interface name (function name), inherited by subclasses to write a function interface
Abstract class defines an interface compatible interface, is outside the caller does not need to worry about the details
Method # interface class constraints subclass must have, and parameters
class Pay_Base:
DEF Pay (Self, Money):
The raise NotImplementedError ( 'Pay MUST BE Implemented The')
class Alpay (Pay_Base):
DEF PAY2 (Self, Money):
Print ( 'Alipay')
class WXpay (Pay_Base):
DEF the pay (Self, Money):
Print ( 'micro-channel pay')
class APpay (Pay_Base):
DEF the pay (Self, Money):
Print ( 'apple payments')
# payment function, an interface function execution object class constraint
DEF Pay (payobj, Money):
payobj.pay (Money)
P1 = Alpay ()
Pay (P1, 100)
7. reflection
It is reflected by a string to operate the object or class or module, a first parameter (object or class or module)
Common:
getter () getattr (parameter 1, 'string') to get memory address #
hasattr () hasattr (parameter 1, 'string') # variable determines whether there
Import M1 class A: local = ' Beijing ' DEF the __init__ (Self): Pass DEF datetime1 (Self): Print ( ' Time ' ) A1 = A () # get property from the object by the reflected B = getattr (A1, ' local ' ) # take by reflection from the class attribute C = getattr (A, ' local ' ) # get reflected from the subject by the method D = getattr (A1, ' datetime1 ' ) #By reflection from the module to get Class B B = getattr (M1, ' B ' )
print(hasattr(m1,'B'))
e = B()
8. The method of the special-bis
__str__ and __repr__, do not understand, but the memory address can be read into a string object
__call__ method, when the object + () method of the case will execute __call__
A class:
DEF the __init __ (Self, name):
the self.name = name
DEF __str __ (Self):
return the self.name
DEF the __call __ (Self, args *, ** kwargs):
Print (args, kwargs)
return args, kwargs
DEF __ __repr (Self):
return 'str has not executed the repr'
A1 = a ( 'Lucy')
# object execution method __str__
Print (A1)
# __call__ method performed
a1 (1, 2, 3, n . 1 =, m = 2)
# __repr__ direct object execution method
Print (the repr (A1))
# See methods how many objects
print (dir (a1))
__new__ method, new method is a method object base class, the constructor is to open up the memory, to create objects
class A: DEF __new__ is (CLS, args *, ** kwargs): Print ( ' . 1 ' ) cls.name = ' the LOP ' return . Object __new__ is (CLS) # reference obeject c language function to create the object DEF the __init__ (Self) : Print ( ' 2 ' ) # Step __new__ method executing the content, the name of the object is returned to the value A1 # Step __init__ executed to initialize the object A1 = a () Print (a1.name)
A2 = A ()
Print (IS A1 A2) each with two objects # False memory
## Singleton ##
class A:
__instance = None
DEF __new __ (CLS, * args, ** kwargs):
IF CLS .__ instance == None:
CLS .__ instance = Object .__ new new __ (CLS)
# __instance singleton object from the recording memory
return cls .__ instance
A = A1 ()
A2 = A ()
Print (IS A1 A2)