Python object-oriented summary, python object-oriented

Source: Internet
Author: User

Python object-oriented summary, python object-oriented

1. Object-oriented

1. process-oriented

A. Advantages: This greatly reduces the complexity of writing programs. You only need to stack the Code following the steps.

B. Disadvantages: a set of pipelines or processes is used to solve a problem. The Code is to take the lead and

2. Object-oriented

A. Advantage: it solves the scalability of a program. If a single object is modified, it will immediately be reflected in the entire system.

B. Disadvantages: Poor controllability, unable to accurately predict the problem handling process and results in a process-oriented programming pipeline, once an object-oriented program starts, there will be interaction between objects to solve the problem.

3. Category: things with the same characteristics (human, dog, and tiger)

4. Object/instance: a specific thing (Hua next door and wangcai downstairs)

5. instantiation: Class --> Object Process

6. In python, variables are used to represent features, and functions are used to represent skills. Therefore, a class of things with the same features and skills are 'class ',

7. objects are specific to this type of thing.

Class Person: # define a human role = 'person '# attributes of a person's role are all people def walk (self): # people can walk, that is, there is a way to walk, also called dynamic attribute print ("person is walking... ")
Class name: class Attribute = None def _ init _ (self, object attribute): self. object Property = Object Property def method name (self): pass instance = Class Name (10) instance. method Name ()

8. Two Functions of a class: attribute reference and instantiation

9. Attribute reference (class name. Attribute)

Class Person: # define a human role = 'person '# attributes of a person's role are all people def walk (self): # people can walk, that is, there is a walking method print ("person is walking... ") print (Person. role) # view the role attribute print (Person. walk) # reference a person's walking method. Note that this is not called

10. Examples: The class name is instantiated, And the _ init _ function is automatically triggered. You can use it to customize your own features for each instance.

Class Person: # define a human role = 'person '# The role attributes of a person are def _ init _ (self, name): self. name = name # each role has its own nickname; def walk (self): # people can walk, that is, there is a way to walk print ("person is walking... ") print (Person. role) # view the role attribute print (Person. walk) # reference a person's walking method. Note that this is not called

11,

Class Name. class Attribute Class Name. method Name instance = Class Name (parameter, parameter) # The instance is an object instance. method Name () instance. adds a property instance to an object property instance. new property name = 1000 print (instance. new attribute name)

12,About self

Self: the object/instance itself is automatically passed to the first parameter of _ init _ during instantiation. You can also give it a specific name. an object/instance has only one function: attribute reference
Class name: def _ init _ (self, parameter 1, parameter 2): self. object Property 1 = parameter 1 self. object Property 2 = parameter 2 def method name (self): pass def method name 2 (self): pass object name = Class Name (1, 2) # object is an instance, represents a specific thing # Class Name (): class name + brackets is to instantiate a class, which is equivalent to calling the _ init _ method # Passing parameters in brackets, you do not need to pass self to the parameter. The other parameters correspond to each other in init # An object name is returned in the result. object attribute 1 # view object attributes and use the object name directly. the property name can be the object name. method Name () # Call the method in the class and directly use the object name. method Name ()
Dir (class) # Return the list of all names in the class isinstance (object, class) # determine whether the object is an instance of the class print (Person. _ dict _) # The returned dictionary key is the property name, and the value is the property value print (Person. _ module _) # print (person. _ name __, type (Person. _ name _) # Class name of the string data type

13. Class namespaces and objects and instance namespaces

A. a common class creates a namespace for the class to store all the names defined in the class. These names become attributes of the class.

B. The class has two types of attributes: static and dynamic.

  • Static attributes are variables defined directly in the class.
  • Dynamic attributes are the methods defined in the class.

When you create an object/instance, an object/instance namespace is created to store the object/Instance name, which is called the object/instance attribute.

Combination of surface and phase objects:

A combination refers to a group in a class that uses the object of another class as the data attribute.

Column:

from  math  import piclass Circular:    def __init__(self,radius):        self.radius=radius    def area(self):        return self.radius **2 * pi    def perimeter(self):        return 2 * self.radius * picircu=Circular(10)print(circu.area())print(circu.perimeter())
Circle perimeter and area

14. Three features of object-oriented

A. Inheritance

Class Animal: # parent class base class superclass def _ init _ (self, name, life_value, aggr): self. name = name self. life_value = life_value self. aggr = aggrclass Person (Animal): # subclass derived class passclass Dog (Animal): # subclass derived class passegg = Person ('egon',) print (egg. name) print (egg. aggr

Python2class Dad: # classic class Dag (object) # New class python3class Dad = class Dag (object) # New class

1. inherited syntax

Class name (parent class name): You want to call the parent class method in the subclass within the class -- super (subclass name, self ). method Name () outside the class -- super (subclass name, object name ). method Name () if the inherited parent class is not specified, by default, all attributes and methods of the parent class can be used to inherit the object subclass. If the subclass has its own method, it will execute its own method. If the subclass does not have a method, it will execute the parent class. If the subclass has no parent class this method returns an error.


Inheritance, abstraction, and Derivation
InheritanceIs from a large scope to a small scope
AbstractionSmall Scope to large scope
DerivedA subclass-derived class is generated based on the parent class.
In the parent classNoneBut some sub-classes -- derived Methods
Derived attributes
Method Rewriting
Methods In the parent class are implemented again in the subclass.
 

2. Inheritance:

B: Inherit the base classAnd make your own changes or extensions (code reuse)

A: declare that a subclass is compatible with a base class and define an Interface class,Interface Class Definition

Some interface names (that is, the function name) But does not implement the interface function. The subclass inherits the interface class and implements the functions in the interface.

B. Encapsulation

1. Advantages:

A. Isolate changes

B. Encapsulation

C. improve reusability

D. Improve Security

2. encapsulation principles:

A. Hide all content that does not need to be provided externally

B. Hide all attributes and provide public methods for accessing them.

3. Private variables and private methods

A,In python, hide the attribute with double dashes (set private)

Property

Property is a special property. When you access it, a function is executed and the returned value is

C. Polymorphism: "polymorphism refers to a type of things with multiple forms (for example, teachers. the bell rings (), student. when the next class bell rings (), the teacher performs off-duty operations and the students perform out-of-school operations. Although the messages are the same, the results are different)

Polymorphism refers to a kind of object.Multiple statuses

Python built-in polymorphism: Polymorphism: Multiple statuses of the same type of things are polymorphism everywhere in python, But we generally cannot find that we do not need to care about the data type of this object during operations, you just need to use it.

 

15. Reflection

1. Reflection: You can use a string to access object attributes and call object methods (but not methods). reflection can be used for all objects in python.

2. There are four methods for reflection:

Hasattr: hasattr (object, name) determines whether an object has the name attribute or name method. If yes, True is returned. If no, False is returned.

Getattr: gets the attributes or methods of an object. If so, it is printed. Supporting use of hasattr and getattr

Note that if the returned method is the object's memory address, you can add a pair ()

Setattr: assign a value to the object property. If the property does not exist, create a value first.

Delattr: deletes an attribute specified by this object.

A. built-in methods:Isinstance and issubclass

Isinstance (obJ, cls) Check whether obj is a classClsOfObject

class Foo:    passclass Son(Foo):    passs=Son()print(isinstance(s,Son))

B. built-in methods:Issubclass (sub,Super) Check subWhether the class isSuperSchool of ClassesClass 

class Foo(object):    pass class Bar(Foo):    pass issubclass(Bar, Foo)

 

C,Reflection in python object-oriented: operations on Object-related attributes in the form of strings. Everything in python is an object (reflection can be used)

Check whether a property exists --- hasattr returns a Boolean value to obtain the property --- If getattr does not exist, an error will be reported when setting the property --- setattr Delete the property --- delattr

D. built-in methods:_ Del __

The Destructor is automatically triggered when an object is released in the memory.

Note: This method is generally not needed to be defined. Because Python is a high-level language, programmers do not need to worry about memory allocation and release when using it, because this job is to be executed by the Python interpreter, the Destructor is automatically triggered by the interpreter during garbage collection.

class Foo:    def __del__(self):        print('fgs')f=Foo()print(123)print(123)del fprint(123)print(123)print(123)

 

E. built-in methods:Item Series

_ Getitem __\__ setitem __\__ delitem __

_ New __

Class A: def _ init _ (self): # There is A way to help you create self print ('in init function') self. x = 1 def _ new _ (cls, * args, ** kwargs): print ('in init funct ') return object. _ new _ (A, * args, ** kwargs) a = ()

F, _ str _ and _ repr _ change the string display of the object

Class Foo: 2 def _ init _ (self, name): 3 self. name = name 4 def _ repr _ (self): 5 return 'obj in str' # return 6 # def _ str _ (self ): 7 # return '% s obj in str' % self. name 8 f = Foo ('egon') 9 print (f) # preferentially execute the content 10 in _ str _ # Are you useless? 11 # print ('% s' % f) # The returned value in _ str _ is executed. 12 # print (' % R' % f) # The returned value 13 print ('=') 14 print (str (f) in _ repr )) # When str (f) is executed, the _ str _ method will be searched. If not found, __repr _ this method is replaced by 15 print (repr (f) 16 #1. when printing an object, if the _ str _ method is implemented, print the return value 17 #2 in _ str. when _ str _ is not implemented, the _ repr _ Method 18 #3 is called. however, when you format the string, % s and % r will respectively call the _ str _ and _ repr _ Methods 19 #4. the 20 # _ repr _ method can be used as a substitute for the _ str _ method when the string is formatted or the object is printed, but not 21 #5. used A friendly representation object. If the _ str _ and _ repr _ methods are used, you can only implement one: First implement _ repr __
_ Str __,__ repr __

15. built-in Methods

A. Static methods and class methods

1. Class Method: There is a default parameter cls, which can be called directly by class name and can interact with class attributes (that is, class attributes can be used)

2. Static Method: Make the methods in the class directly called by the class, just like calling a function normally.

B. Similarities between class methods and static methods: they can be called directly by class without instantiation.

C. Differences between class methods and static methods:

The class method must have a cls parameter to represent this class. class attributes can be used.

Parameters are not required for static methods.

D. Bind Methods: common methods and class methods

Common method: by default, a self object is passed in and can only be called by the object ------- bound to the object

Class Method: by default, a cls object is passed in, and can be called by class and object (not recommended) ----- bound to class

E. Non-binding method: static method: no default parameters are set and can be called by classes and objects (not recommended) ----- non-binding

16. Interface Class and abstract class

A. Interface Class: (based on the abstract class)

In python, there is no interface class by default.

Interface classes cannot be instantiated (if instantiated, an error is reported)

Methods In the interface class cannot be implemented

The interface is a constraint, so that the methods of the following classes are defined according to the methods given in the interface class. If some method classes in the interface class do not exist, the class cannot be instantiated. (Literally) The second meaning of inheritance is very important. It is also called "interface inheritance ". Interface inheritance essentially requires "to make a good abstraction, which specifies a compatible interface, so that external callers do not need to care about specific details, all objects of a specific interface can be processed equally. "This is called normalization in programming.

B. abstract class

In python, the default method is the method of some parent classes. The subclass must implement the abstract class (parent class) method to be implemented.
The difference between an abstract class and an interface class: an interface class cannot implement a method. An abstract class can implement the same content of the abstract class and the interface class in the method: both are used for constraints, can not be instantiated abstract class and Interface Class use: when the parent classes of several sub-classes have the same function needs to be implemented, use abstract class when several sub-classes have the same function, but when the implementation is different, the interface class is used.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.