Python basics-Object-oriented programming

Source: Internet
Author: User
Tags access properties

Classes and objects

2 very important concepts of object-oriented programming: Classes and objects

Objects are the core of object-oriented programming, and in the process of using objects, in order to abstract define a set of objects with common characteristics and behaviors, another new concept-class

The class is equivalent to the drawing of the aircraft, and the aircraft used to create it is equivalent to the object

1. Class
人以类聚 物以群分。具有相似内部状态和运动规律的实体的集合(或统称、抽象)。 具有相同属性和行为事物的统称

Classes are abstract and often find a specific existence of this class when used, using this specific existence. A class can find multiple objects

2. Objects
某一个具体事物的存在 ,在现实世界中可以是看得见摸得着的。可以是直接使用的

 

3. Relationships between classes and objects

Small summary: A class is a template for creating objects

Defining classes

Define a class with the following format:

class 类名:    方法列表

Demo: Define a Car class

# 定义类class Car:    # 方法 def getCarInfo(self): print(‘车轮子个数:%d, 颜色%s‘%(self.wheelNum, self.color)) def move(self): print("车正在移动...")

Description

    • There are 2 ways to define a class: The new class and the classic class, the car above is the classic class, and if it is car (object) It is a modern class
    • The naming rules for class names follow the "Big hump"

Creating objects

A car class was defined in the previous lesson; it is like having a vehicle with a drawing, then we should give the drawing to the generator to generate

In Python, you can create objects based on the classes you've defined

The format of the created object is:

    对象名 = 类名()

Create Object Demo:

#Defining ClassesclassCar:#Moving    defMove (self):Print('the car is running ...')    #Whistle    defToot (self):Print("the car is whistling ... Doodle..")#create an object and use the variable BMW to save its referencesBMW =Car () Bmw.color='Black'Bmw.wheelnum= 4#Number of wheelsBmw.move () bmw.toot ( )Print(Bmw.color)Print(Bmw.wheelnum)

Summarize:

    • BMW = Car (), which produces an instance object of car, which can also be accessed by the instance object BMW to access properties or methods
    • The first time you use Bmw.color = ' black ' to add a property to the BMW object, if it appears again Bmw.color = XXX indicates that the property was modified
    • BMW is an object that has attributes (data) and methods (functions)

__init__()Method

Think about it:

In the previous section of the demo, we have added 2 properties to the BMW object, Wheelnum (number of tires of the car) and color (car color), imagine if you create an object again, it must also be added properties, obviously it is very troublesome, Is there any way to set the properties of the car object when creating the object?

For:

__init__()Method

<1> How to use
def 类名:    def __init__(): pass
<2> __init__()Invocation of the method
#Define Car classclassCar:def __init__(self): Self.wheelnum= 4Self.color='Blue'    defMove (self):Print('the car is running, target: Hawaii')#Creating ObjectsBMW =Car ()Print('the car's color is:%s'%Bmw.color)Print('number of tires for car:%d'%bmw.wheelnum)

Summary 1

When the car object is created, __init__() BMW has a default of 2 properties Wheelnum and color without invoking the method, because the __init__() method is called by default immediately after the object is created.

Think about it.

Now that the method has been executed by default after the object has been created __init__() , can you let the object __init__() pass some parameters when invoking the method? If so, how do you pass it?

#Define Car classclassCar:def __init__(self, Newwheelnum, Newcolor): Self.wheelnum=Newwheelnum Self.color=NewcolordefMove (self):Print('the car is running, target: Hawaii')#Creating ObjectsBMW = Car (4,'Green')Print('the car's color is:%s'%Bmw.color)Print('Number of wheels:%d'%bmw.wheelnum)

Summary 2

    • __init__()method, which is called by default when an object is created, and does not need to be called manually
    • __init__(self), by default there are 1 parameters whose name is self, and if 2 arguments are passed when the object is created, then the self __init__(self) as the first parameter requires 2 formal parameters, for example__init__(self,x,y)
    • __init__(self)Does not need to be passed by the developer, the Python interpreter will automatically pass in the current object reference.

Defined __str__()Method
classCar:def __init__(self, Newwheelnum, Newcolor): Self.wheelnum=Newwheelnum Self.color=Newcolordef __str__(self): Msg="hey ... My color is"+ Self.color +"I have"+ int (self.wheelnum) +"a tyre ..."        returnmsgdefMove (self):Print('the car is running, target: Hawaii') BMW= Car (4,"White")Print(BMW)

Summarize:

    • In Python, if the method name is __xxxx__() , then there is a special function, so called "magic" method
    • When using the print output object, as long as you define the __str__(self) method, you will print the data return from this method

Understand self
#define a classclassAnimal:#Method    def __init__(self, name): Self.name=namedefPrintname (self):Print('name is:%s'%self.name)#Define a functiondefmyprint (animal): Animal.printname () Dog1= Animal ('Sissy') Myprint (dog1) dog2= Animal ('North North') Myprint (DOG2)

Execution Result:

Summarize:

    • The so-called self, can be understood as oneself
    • Self can be understood as the this pointer inside a class in C + +, which means the object itself
    • When an object calls its method, the Python interpreter passes the object as the first argument to self, so the developer only needs to pass the following arguments

__del__()Method

After the object is created, the Python interpreter calls the method by default __init__() ;

When you delete an object, the Python interpreter also calls a method by default, which is the method __del__()

Import TimeclassAnimal (object):#Initialize Method    #is automatically called when the object is finished creating    def __init__(self, name):Print('The __init__ method is called') self.__name=name#destructor Method    #when the object is deleted, it is automatically called    def __del__(self):Print("The __del__ method is called")        Print("the%s object was immediately killed ..."%self.__name)#Creating ObjectsDog = Animal ("Hello, dog .")#Delete ObjectdelDogcat= Animal ("Persian cat") Cat2=CATCAT3=CatPrint("---Delete cat objects immediately")delCatPrint("---Delete the Cat2 object immediately")delCat2Print("---Delete the Cat3 object immediately")delCAT3Print("program ends in 2 seconds") Time.sleep (2)

Operation Result:

Summarize:

    • When there are 1 variables that hold a reference to the object, the reference count of this object is added 1
    • When using Del to delete the object pointed to by the variable, if the object's reference count is not 1, such as 3, then it will only let the reference count minus 1, that is, to 2, when the Del is called again, 1, if the call 1 del, this will actually delete the object

Python basics-Object-oriented 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.