An explanation of the object-oriented Automation operations Python series

Source: Internet
Author: User
Object-Oriented Programming

Process oriented: From top to bottom code based on business logic

Function: Encapsulates a function code into a function, which is called directly at a later time and does not need to be written again

Object-oriented: classify and encapsulate functions to make development "faster, better and stronger ..."

# programming languages like Java and C # support object-oriented programming only, while Python supports functional programming and object-oriented programming mixing

Object-oriented Example

# Functional Programming def bar ():    print (' Bar ')  bar ()  # Direct call to function # Object-Oriented Programming class Foo:  # Create Class       def bar (self):  # Define a function inside a class here self is a special parameter to create an object when Foo passes itself in        print (' bar ')  obj = Foo ()  # Create an Object Obj.bar ()  # object to access the function inside the class

Three main features of object-oriented: encapsulation inheritance polymorphism

Packaging

Encapsulate what we need into the created class and call it when needed

Class Foo:  # to create      def __init__ (self, Name, age):  # Foo receives two parameters and encapsulates it inside its own class        Self.name = Name        Self.age = age    obj = Foo (' kobe ', +)  # Create an object pass two parameters print (Obj.name, obj.age)  # Outside call the encapsulated parameter  output: Kobe 18

Class Member

Fields: Normal fields, static fields

Methods: Common method, static method, class method

Properties: Normal Properties

1) fields (parameters encapsulated within the class)

Class Foo:    # field (static field saved in Class)    CC = "China"    def __init__ (self, name):        # field (normal field is saved in object)        Self.name = name  # Normal field access by object obj = Foo (' Shanghai ') print (obj.name) # static field access print (foo.cc) through class

2) methods (functions encapsulated within the class)

Class Foo:      def Show (self):              # Normal Method: Object call execution method belongs to class        print (self.name)      @staticmethod    def f1 ():        # The static method is executed by the class call        to execute print (' F1 ')      @classmethod    def f2 (CLS):  # class automatically passes in the class name #        classes Method        # CLS is the class name plus () Create Object        print (CLS)  # Create Object obj = Foo () # through the object to access the normal Method Obj.show () # Through the class to access the static Method Foo.f1 () # class method will pass the class Foo name directly into the function foo.f2 ()

3) Properties

Before we can define the properties of a class, we need to append parentheses () to the method name (): For example, OBJ.F1 ()

After defining the attributes, we can access the methods in the class directly obj.f1

Class Foo:    @property    def F1 (self):        print (' F1 ')  obj = Foo () obj.f1  # without parentheses directly through object access

Can be set, can be deleted

Class Foo:      @property  # Add the property decorator Def F1 (self) on the class method     :        print (' F1 ')      @f1. Setter  # Set the value    def F1 (self, values):        print (values)      @f1. deleter  # can delete    def F1 (self):        print (' del ... ')  obj = Foo () obj.f1  # without parentheses directly through the object access  obj.f2 = 100del obj.f1  output: F1del ...

Another way of writing a class property

Class Foo:      def F1 (self):        return      of Def f2 (self, value):        print (value)      Def-F3 (self):        The print (' + ')           # class attribute defines Foo = Property    (fget=f1, Fset=f2, fdel=f3)  obj = Foo ()  # value ret = obj. Fooprint (ret)  # Assignment obj. Foo = $  # delete del obj. Foo  # Output 100200300

Class member Modifiers

Class member modifier: Defines a field or method in a class as public or private

Public members: accessible from anywhere

Private members: can only be accessed within the class

Class Foo:      __cc = 123      def __init__ (self, name):        self.__name = name  # Plus two underscore __ indicates private field outside, inheritance cannot call      def F1 (self):        print (self.__name)      @staticmethod  # Plus Staticmethod adorner is represented as a static method and can be called directly outside the Def F3 without the self parameter    ( Self):        print (foo.__cc)  obj = Foo (' kobe ') # print (obj.__name)  # External access via object internal Normal field is not successful obj.f1 ()  # Print ( FOO.__CC)  # through external access internal static field also unsuccessful obj.f3 ()  # Special access method print (Obj._foo__name)

Special members of the class

Description information for __doc__ # classes

__MODULE__ # which module the current object is in

__CLASS__ # which class the current object belongs to

__STR__ # value returned when printing an object

__INIT__ # Construction method

__del__ # destructor method

__call__ # object after parentheses trigger execution

__DICT__ # class or all members in an object

__GETITEM__ # Index operations such as dictionaries

__SETITEM__ # Index Operations

__DELITEM__ # Index Operations

1) __doc__ Description information

Class Foo: "" "Comment __doc__" ""    obj = Foo () print (obj.__doc__) output: Comment __doc__2) __module__ and __class__from Lib.aa Import C  obj = C () print obj.__module__  # output LIB.AA, i.e.: Output module print obj.__class__      # output LIB.AA.C, i.e. output class

3) __init__ and __str__

Class Foo:      def __init__ (self, Name, age):  # construction Method        Self.name = name        Self.age = Age    def __str__ (self):  # str Method        return '%s-%s '% (Self.name, self.age)  obj1 = foo (name= ' Kobe ', age=18) obj2 = foo (name= ' Jordan ', age=18) print (obj1) print (OBJ2) # output: kobe-18 jordan-18

4) __del__

Class Foo:       def __init__ (self, Name, age):  # construction Method        Self.name = name        Self.age = Age       # Destructor: Perform    def __del__ (self) before garbage collection:        Pass

5) __call__

Class Foo:      def __call__ (self, *args, **kwargs): The        print (' call ')  P = Foo ()  # object is followed by parentheses to execute the __call__ method P () # A parenthesis is a class that creates an object two parentheses is to execute the __call__ method foo () ()  # output: Callcall

6) __dict__

Class Foo:       def __init__ (self, Name, age):  # construction Method        Self.name = name        Self.age = age   obj1 = Foo (name= ' Kob E ', age=18)  # Gets the encapsulated data in the object returns a dictionary ret = obj1.__dict__print (ret) # output: {' name ': ' Kobe ', ' age ': ' +}  # All class method # print ( FOO.__DICT__)

6) __getitem__ __setitem__ delitem__ for index operations, such as dictionaries: you can get values, set, delete

Class Foo:      def __getitem__ (self, item):        print (' GetItem ')      def __setitem__ (self, Key, value):        print (' SetItem ') print (Item.Start, item.stop, Item.step)      def __delitem__ (self, key):        print (' Delitem ')  # The bracket syntax automatically executes the GetItem method obj = Foo () obj[' ab ']  # in parentheses and assigns a value to execute the SetItem method obj[' k1 '] = 111del obj[' K1 ']  # Slicing is also going to perform the SetItem method ob J[1:6:2]  # output SETITEMDELITEMGETITEM1 6 2

7) __iter__, __isinstance__, __issubclass__

Class Bar:    Pass  class Foo (bar):         # Returns an object that can be iterated    def __iter__ (self):        # return ITER ([11, 22, 33, 44]        yield 1        yield 2  obj = foo () for item in obj:    print (item)  # See if obj is an instance of Foo = Isinstance (ob J, Foo) # You can also see if it is an instance of the parent class # ret = Isinstance (obj, Bar) print (ret)  # to see if Foo is a subclass of Bar Ret1 = Issubclass (foo, bar) print (r ET1)  # output 12TrueTrue

Super

Super is designed to solve multiple inheritance problems in Python and forcibly executes methods in the parent class.

Class C1:      def F1 (self):        print (' C1.f1 ')  class C2 (C1):      def-F1 (self):        # The F1 method to actively execute the parent class        super (C2, Self). F1 ()        print (' c2.f1 ')  obj = C2 () obj.f1 () # Output: c1.f1c2.f1

Use super to add functionality without changing source code conditions

Catalog Backend  -commons.pyindex.pylib.pysetting.py  commons.py >>class Foo:    def F1 (self):        print (' Foo.f1 ')  index.py >>from setting import classnamefrom setting import Path  def execute ():    model = __ Import__ (Path, fromlist=true)    CLS = GetAttr (model, ClassName)    obj = CLS ()    obj.f1 ()  if __name__ = = ' __ Main__ ':    execute ()  setting >># Path = "Backend.commons" # ClassName = ' Foo '  path = ' lib ' ClassName = ' Myfoo '  lib >>from backend.commons import Foo  class Myfoo (foo):      def F1 (self):        print (' Before ')        super (Myfoo, self). F1 ()        print ("after") so that the results of our own added Lib are as follows Beforefoo.f1after

Using super to implement an ordered dictionary

Class Mydict (Dict):      def __init__ (self):        self.li = []        super (mydict, self). __init__ ()      def __setitem__ ( Self, key, value):        self.li.append (key)        super (mydict, self). __setitem__ (key, value)      def __str__ (self):        temp_list = [] for        key in Self.li:            value = Self.get (key)            temp_list.append ("'%s ':%s"% (key, value)) C11/>temp_str = "{" + ",". Join (Temp_list) + "}"        return temp_str  obj = mydict () obj[' k1 '] = 123obj[' K2 '] = 456prin T (obj)  # output {' K1 ': 123, ' K2 ': 456}

Single-Case mode

# Singleton mode is a common software design pattern. In its core structure, it contains only a special class called a singleton class. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system.

Class Foo:      instance = None    def __init__ (self, name):        self.name = name      @classmethod    def get_ Instance (CLS):        if cls.instance:            return cls.instance        else:            obj = CLS (' Alex ')            cls.instance = obj            return obj  obj1 = foo.get_instance () Obj2 = Foo.get_instance () print (obj1) print (obj2) # output <__main__. Foo object at 0x000001c09b130b70><__main__. Foo Object at 0x000001c09b130b70>

Exception handling

While True:      num1 = input (' NUM1: ')    num2 = input (' num2: ')      try:        num1 = Int (NUM1)        num2 = Int (num2)        ret = num1 + num2      except Exception as ex:        print (ex)    except ValueError as ex:        print (ex)    Except Indexerror as ex:        print (ex)

Exception handling complete code

try:raise Exception (' Active error ... ') passexcept ValueError as Ex:print (ex) E Xcept Exception as Ex:print (ex) Else:passfinally:pass 
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.