Python object-oriented and class members and exception handling

Source: Internet
Author: User

Python Object-oriented

You think of yourself as a god, you want to create a planet, first you have to knead it into a ball, two of the diameter can create a ball

classStar:" "name (name), equatorial diameter (equatorial diameter), polar diameter (polar diameter)" "    def __init__(self,name,eqdiameter,podiameter): Self.name=name Self.eqdiameter=eqdiameter#Equatorial DiameterSelf.podiameter=podiameter#Pole diameterself.show ()defShow (self):Print("A Spin star%s,this Ed is%s,pd is%s"%(Self.name,self.eqdiameter,self.podiameter)) Earth=star ("Earth", 24901,24859): A spin star Earth Created,this Ed is24901,pd is24859

Class and object relationships:

Object is an instance of a class

Inherited:

Class B inherits from Class A, the inheritable members of Class A, all of which are Class B, if there are members of Class A, Class B also has a preference for members of Class B, and if the object of Class B is to use the members of Class A, use polymorphism.

Class B Inherits Class A, Class B is derived from Class A, Class A is a class B parent or base class, Class B is a subclass of Class A or a derived class, the method is: Issubclass (C (Child), B (parent))

Polymorphism: A variety of forms------is the subclass of the object can use the members of the parent class, which is already in the member subclass, the object does not satisfy the subclass of this member, to find its parent class method

Inheritance relationships for multiple classes:

Multiple Inheritance instances:

Python class Members:

1, field: Static Field/Normal field

2, Method: Static method/Common Method/class method/Special method

3, properties

4, Member modifier

5, Special method

The members of the class are permissions-controlled, Python's class permissions are only private (private) and common (public), and the flags of the private objects are the members preceded by the Add __

class Province:    Country=" China "      # Static Variables    __party="comunity"      # private static member

Private members can only be used inside the current class and cannot be used for objects and inheriting classes

Field:

A field is a data member, a static field is stored in a class, a normal field is stored in an object, each object creation needs to open up the memory space of a normal field, and a static field is only required to stay in the space of the class, so when there are too many normal fields, if you determine that a variable is initially fixed, You can turn this variable into a static field.

Method:

Methods are classes, common methods are executed by objects, static methods and class methods are executed by the class, do not create objects, save space, class methods specify the current class

@staticmethod Defining static methods

@classmethod Defining class methods

classProvince:country="China"      #Static Variables    __party="comunity"      #private static Members    def __init__(self,name): self. Myparty=self.__party      #Common VariablesSelf.__name=name#private, cannot inheritself.f1 () self.__f1()    defShow (self):#Normal object, called by the object.        Print(self.)__name) @staticmethod#static methods, called by class, can be used inside classes    defF1 ():Print("FL") @staticmethoddef __f1(self):#private static Methods        Print("Private FL") @classmethod#class Method    defF2 (CLS):Print(CLS)

Attribute members:

Looks like a method, used like a field, adorner: @property

Properties can print values, assign values, delete values

classprofact:" "Retrofit Plant" "@property#Properties    defF3 (self):return10@f3. Setter#You can assign a value to a property    deff3 (self,value):Print(value) @f3. deleter#Delete Property    defF3 (self):Print("deleted") A=profact () result=a.f3#The F3 is called under the property.A.f3=12#Call the F3 under @f3.setterdelA.f3#Call the F3 under @f3.deleter

Special Members:

Function

Description

Example

__init__

constructors, creating objects

__del__

Destructors, Garbage collection

__call__

Call the object as a function call when there is () behind the object

A=a ()

Print (A ())

__str__

Print Call

Print (a)

__add__

This + other

__sub__

This-other

__iter__

Automatically called when iterating, can be combined with yield

__getitem__

Receive Key,key receive slice 1:2:3 corresponding Key.start

Key.stop

Key.step

a["DDD"]

__setitem

Receive key and value

a["ddd"]= "dddd"

__delitem__

Receive key

Del a["DDD"]

Exception handling:

When a user creates a directory, there is no guarantee that the directory does not exist

When a user deletes a directory, there is no guarantee that the directory exists, nor does it guarantee that the directory is empty

All of these conditions will cause an exception, which will cause the program to terminate, and these are clearly not the problem caused the program to terminate, such as these we know the error will be the program can be handled with exception, display friendly error prompts, improve the user experience

Import Osos.mkdir ("KKK")    # KKK directory exists in case of execution Traceback (most recent):   " f:/project/pysession/day08/exception handling. PY "  in <module>    os.mkdir ("KKK"'  KKK'

After transformation:

Import OS Try :    Path="KKK"    os.mkdir (path)except  Fileexistserror:    print("%s directory already exists "%path)

As the above determines the type of error can be directly with the error type, if you cannot determine the type of error can also be used exception:

Import OS Try :    Path="KKK"    os.mkdir (path)except  Exception:    print("%s directory already exists "%path)

A complete capture:

ImportOSTry: Path="KKK"os.rmdir (path)exceptFilenotfounderror:Print("%s directory does not exist"%path)exceptOSError:Print("%s directory is not empty"%path)exceptException:Print("%s directory cannot be error"%path)Else:#execute only in the correct case    Print("%s directory successfully deleted"%path)finally:#whether it's wrong or right, execute    Print("directory Delete to this end")

I can make my own mistakes raise < error type > ("< error message >"):

Raise Exception (" error ") Error: Exception: Error

You want to catch the error and display the error message:

Try :     Raise Exception (" error ")except  Exception as errormsg:      Print(errormsg)

Define the error type yourself:

class myexception (Exception):     def __init__ (self,errormsg):        self.errormsg=errormsg    def__str__(self):         return self.errormsg Raise MyException (" wrong ") concluded:__main__. MyException: something went wrong.

Python object-oriented and class members and exception handling

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.