The path to Python (22nd) Object-oriented: Concepts, class properties

Source: Internet
Author: User
Tags class definition

I. Object-oriented concept1. What is Object-oriented (OOP)?

To put it simply, "object-oriented" is a programming paradigm, and programming paradigms are programmed according to different programming features. As the saying goes, all roads lead to Rome, it is said that we use different methods can achieve the ultimate goal, but some methods are relatively fast, safe and effective, some of the method is inefficient and unsatisfactory effect. Similarly, the programming is to solve the problem, and solve the problem can have a variety of different perspectives and ideas, the predecessors of some of the most widely applicable and effective programming model attributed to the "paradigm." The common programming paradigms are:

    • Process-oriented Programming: OPP (Procedure oriented programing)

    • Object-Oriented Programming: OOP (Object oriented programing)

    • Functional Programming: (Functional programing)

process-oriented programming steps:

1) Analyze the steps needed to solve the problem;

2) Use the function to implement these steps one at a time;

3) One by one to call these functions to solve the problem;

Process-oriented programming: The core is the process of two words, the process refers to the steps to solve the problem, that is, what to do first ... Process-oriented design is like a well-designed pipeline, is a mechanical way of thinking.

The advantage is: the complexity of the problem flow, and then simplification (a complex problem, divided into small steps to achieve, the implementation of small steps will be very simple)

The disadvantage is: a set of pipeline or process is to solve a problem, the production line of soda can not produce a car, even if it can, also have to be big change, change a component, reaching.

Application scenario: Once you have completed a very rarely changed scenario, the notable examples are Linux kernel, git, and Apache HTTP server.

object-Oriented programming steps:

1) The decomposition and abstraction of the affairs of the constituent problems into the various objects;

2) combine the common attributes of these objects and abstract out the classes;

3) class hierarchical structure design--inheritance and synthesis;

4) Use classes and instances to design and implement to solve the problem.

Object-Oriented Programming: The core is the object of two words, the object is a combination of features and skills, based on the object-oriented design program is like in the creation of a world, you are the god of the world, the existence of all objects, not exist can also be created, and process-oriented mechanical mode of thinking in sharp contrast, Object-oriented more attention to the real world simulation, is a "God-style" way of thinking.

The advantages are: easy to maintain, easy to reuse, easy to expand, due to the object-oriented packaging, inheritance, polymorphism characteristics, can design a low-coupling system, making the system more flexible and easier to maintain.

The disadvantage is that the complexity of programming is much higher than the process-oriented, do not understand the object-oriented and immediately get started based on its design program, extremely prone to excessive design problems. Unable to process-oriented programming pipelining can accurately predict the problem of the processing process and results.

Application scenario: frequently changing requirements of the software, the general needs of the changes are concentrated in the user layer, Internet applications, enterprise internal software, games, etc. are object-oriented programming is a good place to play.

2. Features of object-oriented programming

Object-oriented programming achieves the 3 goals of software engineering: reusability, flexibility, extensibility, and these goals are achieved through the following key features:

    • Package: You can hide implementation details and make your code modular

    • Inheritance: You can implement code reuse by extending existing classes to avoid repeating the same Code

    • Polymorphic : The purpose of encapsulation and inheritance is to implement code reuse, and polymorphism is to implement interface reuse, so that classes can be inherited and derived to ensure that any instance of a class can correctly invoke the agreed-upon properties and methods. Simply put, it is to agree on the same property and method name.

3. Object-oriented programming usage scenarios
    • Scenario 1: when multiple functions need to pass in multiple common parameters, these functions can be encapsulated in a class, and these parameters are extracted as properties of the class;

    • Scenario 2: when you need to create something based on a template, you can do it through a class.

noun explanation

class: A class is an abstraction, Blueprint, prototype, template for a class of objects that have the same properties. The properties of these objects are defined in the class (variables (data)), common methods

Properties: human beings contain many characteristics, which are described by programs, called attributes, such as age, height, gender, name, etc. are called attributes, and a class can have multiple properties

Method: human beings have not only height, age, sex these attributes, but also can do a lot of things, such as talking, walking, eating and so on, compared to the attribute is a noun, talking, walking is a verb, these verbs are described by the procedure is called method.

instance (object): An object is an instantiated instance of a class, a class must be instantiated before it can be called in the program, a class can instantiate multiple objects, each object can also have different properties, like human refers to everyone, each person refers to the specific object, people and people before there is a common, there are different

Instantiation: The process of producing an object from a class is called instantiation.

When the software system is running, the class is instantiated as an object (object) that corresponds to a specific thing and is an instance of the class (Instance)

Class is the most important concept of object-oriented design, which is the combination of feature and skill, while class is a combination of features and skills with similar objects.

in the real world: there are objects first, then there are classes

In the real world: first there are objects, then there are classes: the world must first appear a variety of actual objects, and then with the development of human civilization, human standing in different angles summed up the different kinds, such as human, animal, plant and other concepts .

in the program: Be sure to define the class first, then produce the object

This is similar to the use of functions, the function is defined first, the function is called after, the class is the same, in the program needs to define the class, and then call the class

Instead , the calling function executes the function body code that returns the result of the function body execution, and the calling class produces the object, returning the object .

Example: Defining a school class with nested functions
Def school (Name,addr,type):    def init (name,addr,type):        sch = {            "name": Name,            "addr": addr,            "type" : Type,            "enrol_students": enrol_students,            "exam": Exam        }        return sch    def enrol_students (school):        Print ("%s is enrolling"%school["name"])    def exam (school):        print ("%s is exam"%school["name"])    return init (name,addr,type) S1 = School ("Tsinghua", "Beijing", "public") s1["Enrol_students"] (S1)

  

second, class propertiesclass has two properties: Data properties and Function Propertiesobject has only data properties, but can access the function properties of the class

1. The data properties of the class are shared by all objects

2. A function property of a class is used to bind to an object.

A function defined in a class (not adorned by any adorner) is a function property of a class, which can be used, but must follow the function's parameter rules, with several arguments that need to be passed.

The functions defined in the class (which are not decorated by any adorners) are primarily used for objects, and are bound to objects, although all objects point to the same functionality, but binding to different objects is a different binding method.

Emphasis: The special thing about a method that binds to an object is who is bound to whom it is called, and who calls it, and will ' who ' itself as the first parameter passed to the method, that is, the automatic value (method __init__ is the same reason)

Adding and deleting data properties of a class
  
  Class Chinese:      country = "China"  ?      def __init__ (self,name):          self.name = name  ?  P1 = Chinese ("Nick")  # view class Data Properties  print (chinese.country)  ?  # Add Class Data Property  chinese.minority = chinese.__dict__ print (  p1.country)    #China  Print ( p1.minority)   #    A Data property of a class can be called through an instance object  ?  # Modify class Data properties  chinese.country = "China"  print (chinese.__dict__)  ?  ?? # Delete class data properties  del chinese.minority  print (chinese.__dict__)

  

function Properties of the modified class
  
  Class Chinese:      country = "China"  ?      def __init__ (self,name):          self.name = name  ?      def buy_house (self,house):          print ("%s is buying%s"% (Self.name,house))  ?  P1 = Chinese ("Nick")  # view class function Properties  chinese.buy_house (P1, "Villa")  ?  ?  # Add Class function Properties  def shopping (self,place):      print ("%s is buying buy buy"% (self.name,place))  ?  chinese.shopping = Shopping  p1.shopping ("Paris")  ?  ?  # Modify Class Function Properties  def test (self,msg):      print ("test")  chinese.buy_house = Test  p1.buy_house ("msg")  ?  ?  # Delete class function Properties  print (chinese.__dict__)  del chinese.buy_house  print (chinese.__dict__)

  

Adding or deleting properties of the object to be changed
  
  Class Chinese:      country = "China"  ?      def __init__ (self,name,age):          self.name = name          Self.age = Age  ?      def buy_house (self,house):          print ("%s is buying%s"% (Self.name,house))  ?  P1 = Chinese ("Nick")  # View Object Properties  print (p1.age)  print (p1.buy_house)   #对象与类的函数方法绑定了  ?  # increase the object's properties  p1.gender = "Male"  #增加对象的数据属性  print (p1.__dict__)  ?  def shopping (Self,place):      # Increases the object's function property, the object originally only has the Data property, here the added function property needs itself to call itself, cannot use the class __init__ method.      Print ("%s is buying and buying at%s"% (self.name,place))  p1.shopping = Shopping  p1.shopping (P1, "Paris")  print (p1.shopping)  #只是普通函数, is not the object's binding method, each object needs to store function properties, Unable to implement class method optimization  print (p1.__dict__)  ?  # Modify Object Properties  p1.age =   #修改对象的数据属性  print (p1.age)  #20  ?  # do not modify the object's underlying dictionary  p1.__dict__["Age" =  print (p1.age)  ?  ?  # Delete class function Properties  del p1.age  print (p1.__dict__)

  

Note

Example 1

  
  Class Chinese:      country = "China"      li = ["a"]      def __init__ (self,name,age):          self.name = name          self.age = Age  ?      def buy_house (self,house):          print ("%s is buying%s"% (Self.name,house))  ?  P1 = Chinese ("Nick")  p1.li = [12,3]   #这里修改的是对象p1的l数据属性, equivalent to the newly added P1 of the Li Data  property print (p1.__dict__)  P1.li.append ("B")  #由于p1自己没有li数据属性, here is the data property of the class  print (p1.__dict__)  print (chinese.__dict__)

  



Example 2

  
  Country = "Chinese"  class Chinese:      country = "China"  ?      def __init__ (self,name,age):          self.name = name          Self.age = Age          Print ("---", country)   # The result of the country call here is "China", not "Chinese", here this country, just a normal variable      def buy_house (self,house):          print ("%s is buying%s"% ( self.name,house))  ?  P1 = Chinese ("Nick", 18)

  

Python built-in class properties

  
  __DICT__: The properties of a class (containing a dictionary consisting of the data properties of a Class), a dictionary that holds all members of a class (including properties and methods) or all member properties in an instance object  ?  __DOC__: The class's document string, class description information  ?  __NAME__: Class name  ?  __MODULE__: The module where the class definition resides (the full name of the class is ' main.classname ', if the class is in an import module mymod, then Classname.module equals Mymod). The module name that represents the definition of the class that corresponds to the object of the current operation  ?  __BASES__: All parent classes of a class make up elements that contain a tuple of all the parent classes

  

Construction Method

__init__(...)is called a constructor or initialization method that is automatically executed during instantiation of an instance to initialize some of the properties of the instances. Each instance through __init__ the initialized property is unique.

The main role is to instantiate some initialization parameters to the instance, or perform some other initialization work, in short, because this is __init__ only an instantiation, it will be executed automatically.

Common Methods

Defining some of the normal functions of a class is a normal custom function that does not have any adorners in the class.

Or that sort of thing.

the members of a class can be divided into three main categories: fields, Methods, and properties

(a) field

Fields include: normal fields and static fields, they differ in definition and use, and the most essential difference is where the memory is stored in different places,

    • Normal field belongs to object

    • Static fields belong to class

  
  Class Province:  ?      # static field      country = ' China '  ?      def __init__ (self, name):  ?          # normal field          self.name = name  ?  ?  # Direct access to normal field  obj = Province (' Hebei province ')  print obj.name  ?  # Direct access to static field  province.country  ?

  


Definition and use of fields

Analysis: By the above code can be seen "ordinary field through the object to access" "static field through class Access", in use can be seen in the normal field and static field attribution is different.

    • Static field saves only one copy in memory

    • Normal fields save one copy of each object

(ii) method

Methods include: Common methods, static methods, and class methods, three methods in memory belong to the class, the difference is that the calling method is different.

    • Normal method: Called by the object , at least one self parameter, when the normal method is executed, the object that calls the method is automatically assigned to the self; (that is, a function without any adorner in the class)

    • Class method: Called by the class ; at least one cls parameter; When the class method is executed, the class that invokes the method is automatically copied to the CLS ;

    • Static methods: Called by the class , no default parameters;

  
  Class Foo:  ?      def __init__ (self, name):          self.name = name  ?      def ord_func (self): "" "          defines a normal method with at least one self parameter" "  ?          # print Self.name          print ' normal method '  ?      @classmethod      def class_func (CLS): "" "          defines a class method with at least one CLS parameter" ""  ?          print ' class method '  ?      @staticmethod      def static_func (): "" "          defines a static method with no default parameter" ""  ?          print ' static method '  ?  ?  # Call the normal method  F = Foo ()  f.ord_func ()  ?  # Call class method  Foo.class_func ()  ?  # call static method  Foo.static_func ()

  


?
Definition and use of methods

(c) Attributes

There are two ways to define a property:

    • Adorners: Applying adorners on methods (Adorner mode: Apply @property adorner on ordinary methods of Class)

    • Static fields are: Static fields that define values as property objects in a class

Example

  
  Class Goods (object):  ?      @property      def Price:          print ' @property '  ?  obj = Goods ()  obj.price          # automatically executes the @property decorated price method and gets the return value of the method

  

Reference links

[1] http://www.cnblogs.com/yyds/p/7591804.html

[2] http://www.cnblogs.com/linhaifeng/articles/6182264.html

[3] https://www.cnblogs.com/wupeiqi/p/4766801.html

The path to Python (22nd) Object-oriented: Concepts, class properties

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.