Python2 Learning------Basic Syntax 2 (classes, class inheritance, class member functions, defensive programming)

Source: Internet
Author: User
Tags class definition

1. Definition of class and instantiation

#class definitionclassP:"""This is a basic class"""    def __init__(self):#The class member function needs to pass in the Self keyword        """This is a init function of basic class"""        Print "This is a init function ..."; defSub (SELF,A,B):#The class member function needs to pass in the Self keyword        """This is a common function of basic class"""        returnA-b;#class instantiationA=p ();#Calling class methodsPrintA.sub (40,5);#-1

2. Inheritance of Classes

#Inheriting ClassesclassM (p):#parameter is the name of the class that needs to be inherited    """This is a sub-class of basic class"""    def __init__(self):#proprietary functions (with double underscores for function names)        Print "Sub class init function ..."; Self.__test(); defLoopoutputfun (self,n):ifn<0:PrintN"is not a postive integer"Retrun;  forIinchRange (1,n,3):            Printi; Else:            Print "loop output over ..."; def __test(self):#private Functions (the first part of the function has a double stroke)        Print "the private function of a class cannot be called directly by an instance of the class, but only by a proprietary function call (requires the SELF keyword)"; def __my__(self):#proprietary functions (with double underscores for function names)Self.__test(); defdev__ (self,a,b):"""Demonstrating exceptions"""        Try:            returnA/C; exceptexception,e:PrintE.message; def __passtest__(self):"""when the function logic is not well planned, the PASS keyword is used for processing"""        Pass;#instantiation of Subclassesb=m ();#Calling Subclass MethodsPrintB.sub (100, 55); B.loopoutputfun (10); b.__my__();Printb.dev__ (10,2); b.__passtest__();

3.

Python2 Learning------Basic Syntax 2 (classes, class inheritance, class member functions, defensive programming)

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.