Python Notes * Object-oriented Programming OOP

Source: Internet
Author: User

▲ Object-oriented programming OOP

Object oriented programming. OOP takes objects as the basic unit of a program, and an object contains functions for data and manipulating data.

Process-oriented programming treats a computer program as a set of commands, which is the sequential execution of a set of functions. In order to simplify the program design, the process will continue to cut the function into sub-function, that is, the large function by cutting into small block function to reduce the complexity of the system.

Object-oriented programming treats a computer program as a set of objects, and each object can receive messages from other objects and process them, and the execution of a computer program is a series of messages passing between objects.

In Python, all data types can be treated as objects and, of course, objects can be customized. The custom object data type is the concept of class in object-oriented.

▲ Classes and examples

Class is the template for instance instance. An instance is a specific object created from a class.

In Python, the definition class is implemented through the class keyword. Create an instance, implemented through the class name + (). The sample code is as follows:

#defines a student class that inherits objectclassStudent (object):#The __init__ method can force the Name,score property to bind to Self,self to the creation instance itself    def __init__(self, Name, score): Self.name=name Self.score=score#encapsulates the Print_score method, the method of a class The first argument must be self, and the instance is not passed when it is invoked    defPrint_score (self):Print('%s:%s'%(Self.name, Self.score))defGet_grade (self):ifSelf.score > 90:            Print('A')        elifSelf.score > 60:            Print('B')        Else:            Print('C')#create an instance, pass in a parameter that matches the __init__, and self does not passMichael = Student ('Maciael Jackson', 92) Michael.print_score () Michael.get_grade ()

The sample code runs the result:

Maciael jackson:92A

▲ Access Restrictions

If you let the internal properties of the class not be accessed externally, you can add two _ to the name of the property. Properties named after __ are called private variables in Python. Private variables can only be accessed internally and not externally accessible. This makes the code more robust through access-restricted protection.

If you want to allow external code to access and modify private variables, you can add the get () and set () methods to the private variables (attributes) in the class definition.

▲ Inheritance and polymorphism

Define a class animal, and then define a class of dog that inherits from animal. Then dog is the subclass Subclass,animal is the parent class or the base class BaseClass.

When an inheritance relationship exists for two classes, the subclass obtains all the methods of the parent class. Subclasses can also add their own methods, or they can override the parent class's methods. This is polymorphism.

When we define a class, we are actually defining a data type. You can use Isinstance () to determine whether an object is of this type.

The sample code is as follows:

#defines a class that inherits object animalclassAnimal (object):defRun (self):Print('Animal is running!')#defines a subclass of a class animal dogclassDog (Animal):#overriding the Run () method of the parent class    defRun (self):Print('Dog is running!')#add Eat () method    defEat (self):Print('Dog is eating!')#Create an instance of animal Dog1Dog1 =Animal () dog1.run ( )#Create an instance of dog dog2DOG2 =Dog () dog2.run ()Print(Isinstance (Dog1, Animal))Print(Isinstance (Dog1, Dog))Print(Isinstance (DOG2, Animal))Print(Isinstance (DOG2, Dog))# polymorphicdefrun_again (animal): Animal.run () Run_again (DOG1) run_again (DOG2)

Operation Result:

IS wasis running! 

▲ Get Object Information

Type () to determine the type of the object, return type

Isinstance () is used to determine if it is a type that returns a Boolean value

Dir () gets all the properties and methods of the object and returns a list

Hasattr (), GetAttr (), setattr () can manipulate the state of an object directly

The sample code is as follows:

>>> Isinstance ('ABC', str) True>>> Type ('ABC')<class 'Str'>>>> dir ('ABC')['__add__','__class__','__contains__','__delattr__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__getnewargs__','__gt__','__hash__','__init__','__iter__','__le__','__len__','__lt__','__mod__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__rmod__','__rmul__','__setattr__','__sizeof__','__str__','__subclasshook__','Capitalize','Casefold','Center','Count','encode','EndsWith','Expandtabs','Find','format','Format_map','Index','isalnum','Isalpha','ISDEcimal', 'IsDigit', 'Isidentifier', 'Islower', 'IsNumeric', 'Isprintable', 'Isspace', 'Istitle', 'Isupper', 'Join', 'Ljust', 'Lower', 'Lstrip', 'Maketrans', 'Partition', 'Replace', 'RFind', 'Rindex', 'Rjust', 'Rpartition', 'Rsplit', 'Rstrip', 'Split', 'Splitlines', 'StartsWith', 'Strip', 'Swapcase', 'Title', 'Translate', 'Upper', 'Zfill']

Python Notes * Object-oriented Programming OOP

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.