Python Object-oriented

Source: Internet
Author: User

Python Object-oriented programming

Class
The difference between a class and an object
Class is the abstraction of things in the objective world, such as human, ball
An object is a class-instantiated entity, such as football, basketball
Example Description:
Balls can abstract the characteristics and behavior of the ball and then instantiate a real ball entity (instantiation is the object of creation).

The creation format of the class:

Class ClassName:
The contents of the class


Class Fruit:
def __init__ (self): # # #__init__为类的构造函数
Self.name = Name # # # # Class Properties
Self.color = Color
def grow (self): # # #定义grow函数, functions in a class are called methods
Print "Fruit Grow"

* * The method of a class must have a self parameter that can be passed without passing this parameter when the method is called

Method: A function defined in a class

Properties: Variables defined in a class

Instantiation of a class

Objects created by classes are called instantiations

Class Dog ():
def __init__ (self,name,age):
Self.name = Name
Self.age = Age

def sit (self): # #类的方法
Print (Self.name.title () + "is now sitting.")
def roll_over (self):
Print (Self.name.title () + "ROLLWD over!")

My_dog = Dog (' Willie ', ' 6 ') ## #类的实例化

Print ("My dog ' s name is" + my_dog.name.title () + '. ')
Print ("My dog is" + str (my_dog.age) + "years-old")

Results:

My Dog ' s name is Willie.
My Dog is 6 years.

Calling methods
After instantiating a class, you can invoke the method defined in the class by using the period notation

My_dog.sit ()
My_dog.roll_over ()


Results:
Willie is now sitting.
Willie rolled over!

Properties of the class

The properties of a class can be divided into common and private properties by usage, and the property scope of a class depends on the name of the property
Public properties: Properties that can be called in a class and outside a class
Private properties: Properties that cannot be called outside the class and outside of the class
Definition: A member variable that starts with a double underscore is a private property

Instance:

#!/usr/bin/python
class people (object):
color = ' Yellow '
__age = # # # #私有属性
def think (self):
Self.color = ' Black '
Print "I am a%s"% Self.color
Print "I am a Thinker"
Print Self.__age # # #调用类的私有属性
ren = people ()
Print Ren.color
Ren.think ()
~
Execute script
[email protected] day04]# python class1.py
Yellow
I am a black
I am a thinker
30

=====================================================
If you call a private property outside of the class, you are prompted not to find the property
#!/usr/bin/python

class people (object):
color = ' Yellow '
__age = 30
def think (self):
Self.color = ' Black '
Print "I am a%s"% Self.color
Print "I am a Thinker"
Print Self.__age
ren = people ()
Print Ren.color
Ren.think ()
Print Ren.__age # # # #调用类的私有属性
~
Perform
Prompt for property not found
Traceback (most recent):
File "class1.py", line +, in <module>
Print Ren.__age
Attributeerror: ' People ' object has no attribute ' __age '

Methods of the class

The



Public methods: Methods that can be called in and out of class
Private methods: cannot be called outside the class. To precede the method with the "__" double underscore is the private method
self parameter
The method used to differentiate between functions and classes (must have a self) is the Execute object itself
===============================================================
Public Method instance:
#!/usr/bin/python
#coding: UTF8
class People (object):
   color = ' Yellow '
   __age =
def think (self):
    Self.color = ' black '
    print "I am a%s"% SE Lf.color
    print "I am a thinker"
    print self.__age
def test (self):
    S Elf.think ()    ### #调用方法think
Jack = people ()
Jack.test ()

Perform
[email protected] day04]# python class2.py
I am a black
I am a thinker
30

===================================================================
Private Method Instance:

#!/usr/bin/python
#coding: UTF8
class people (object):
color = ' Yellow '
__age = 30
def think (self):
Self.color = ' Black '
Print "I am a%s"% Self.color
Print "I am a Thinker"
Print Self.__age
def __talk (self):
Print "I am talking with Tom"
def test (self):
Self.__talk () # # #调用私有方法talk
Jack = People ()
Jack.test ()

Perform

[email protected] day04]# python class2.py
I am talking with Tom

Inheritance of Classes

When a class inherits from another class, it obtains all the properties and methods of the other class, the original class becomes the parent class, and the new class is called the subclass, and all the properties and methods of the subclass base parent class

Class Car ():

def __init__ (self, make, model, year):
Self.make = Make
Self.model = Model
Self.year = Year
self.odometer_reading = 0

def get_descirptive_name (self):
Long_name = str (self.year) + "+ self.make +" + Self.model
Return Long_name.title ()

def read_odometer (self):
Print ("This car had" + str (self.odometer_reading) + "miles on it.")

Class Electirccar (Car): # # #定义子类ElectricCar
def __init__ (self,make,model,year):
Super (). __init__ (Make,model,year) # # #初始化父类的属性, call Electircar's parent class method __init__ () so that Electirccar contains all the properties of the parent class

My_tesla = Electirccar (' Tesla ', ' Model S ') # #创建ElectircCar类实例, call the parent class car-defined Method __init__ ()
Print (My_tesla.get_descirptive_name ()) #调用父类方法


Execution results
Tesla Model S

# # #创建子类时, the parent class must be contained in the current file and precede the child class, you must specify the name of the parent class within parentheses
Super () to associate a parent class with a subclass


Subclasses define properties and methods

Class Car ():

def __init__ (self, make, model, year):
Self.make = Make
Self.model = Model
Self.year = Year
self.odometer_reading = 0

def get_descirptive_name (self):
Long_name = str (self.year) + "+ self.make +" + Self.model
Return Long_name.title ()

def read_odometer (self):
Print ("This car had" + str (self.odometer_reading) + "miles on it.")

Class Electirccar (Car):
def __init__ (self,make,model,year):
Super (). __init__ (Make,model,year)
Self.battery_size = # #子类属性
def describe_battery (self): # #子类方法
Print ("This car has a" + str (self.battery_size) + "-kwh battery.")

My_tesla = Electirccar (' Tesla ', ' model S ', 2016)
Print (My_tesla.get_descirptive_name ())
My_tesla.describe_battery ()


Execution results

Tesla Model S
This car has a 70-kwh battery.

Python Object-oriented

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.