Python object oriented Foundation

Learning objectives

  • Understanding object orientation
  • Classes and objects
  • Add and get object properties
  • Magic method

I. understanding object orientation

  • Object oriented is an abstract programming idea, which many programming languages have
  • Object oriented is to make a group of data structures and methods to deal with them into objects, summarize objects with the same behavior into classes, hide the internal details of classes by encapsulation, generalize classes by inheritance, and realize dynamic assignment based on object types through polymorphism.
    Encapsulation inheritance polymorphism

Class II and objects

There are two parts of object orientation:
Classes and objects
[relation]: create an object with a class

2.1 understanding classes and objects

2.1. Class 1

Class is the general name of things with the same characteristics and behavior, not real things

  • Characteristics are attributes
  • Behavior is method

2.1. 2 object

Objects are real things created with classes

be careful:
There are classes before objects in development
Define the class, create the object print (object name) and output the memory address

print(haier) #  Print out the memory address, indicating that the object is created successfully
 => <__main__.Class washing machine object at 0x0000000001241BA0>

2.2 object oriented implementation method

2.2. 1 definition class

  • grammar

class name ():
code
...

Pay attention to the class name, and generally follow the big hump rule

2.2. 2 create object

  • grammar

Object name = class ()

2.2. 3 experience

  • Demand: washing machine washing clothes
  • Idea: first define classes, and then create objects with classes

Three steps
1 definition class
2 create requirements
3 verification

  • code
 # Define class
class Class washing machine():
	def function(self):
		print("Can wash clothes")
 # create object
 Haier=Class washing machine()

 # verification
 #Print haier objects
 print(haier) #  Print out the memory address, indicating that the object is created successfully
 => <__main__.Class washing machine object at 0x0000000001241BA0>

 # Use function instance method / function --- object name Function ():
 Haier.function()
=> Can wash clothes

2.2.4 self

self is the object that calls the function
1. A class can create multiple objects,
Multiple objects call the functions of the class, but the address of self is different

Third, add and get the properties of the object

Attributes are features, such as the natural attributes of length, width and weight of the washing machine
Object properties can be added and obtained either outside the class or inside the class

3.1 add object attributes outside the class

  • grammar

Object name Attribute name = value

  • experience

Haier Height = 500
Haier Width = 800

3.2 added in class

  • grammar

Attribute name = value

  • experience

class washing machine ():

Height = 500
Width = 600

#Create object
Haier = washing machine

3.3 get object properties outside the class

Print (Haier. Width) # prints out the memory address, indicating that the object is created successfully
=>600

3.4 get object properties in class

  • grammar

self. Attribute name

  • experience
# --*coding:utf-8*--
# Define class
class Class washing machine():
	# Class to get instance properties
    def print_info(self):
        #self. Attribute name
        print(self.wide)
        print(self.high)
# create object
 Haier=Class washing machine()

# Add instance properties
 Haier.high=500
 Haier.wide=800

# Object calls instance methods
 Haier.print_info()

=>800
=>500

Four magic methods

In Python, the function of xx() is called magic method, which refers to the function with special functions

4.1 init()

4.1. 1 experience init()

Thinking about the height and width of the washing machine is a natural attribute, so give these attributes in the production process

==init() is used to initialize objects==

  • grammar

def init(self):

self. Width = 500
self. Height = 600

  • thinking

1 definition class

init magic method: width and height
Add instance method: access instance properties

2 create object
3. Successful verification

Offset instance method

  • experience
# --*coding:utf-8*--
# Define class
class Class washing machine():
    # Definition__ init__ (). Add instance properties
    def __init__(self):
        #Add instance properties,
        self.wide=600
        self.high=500
    def Print information(self):
        #Class to call instance properties
        print(self.wide,self.high)

# create object
 Haier=Class washing machine()

# verification
 Haier.Print information()

be careful:

  • The init() method does not need to be called manually when creating an object, but will be called automatically
  • The self parameter in init(self) does not need to be passed by the developer. It automatically passes the reference of the current object

4.1. 2 init with parameters ()

A class can create different objects. How to set different initialization properties for different objects

  • [thinking] a washing machine class can create two washing machines of Haier and Hisense. How to set their different initialization attributes
  • grammar

init(self, width, height)

  • experience
# --*coding:utf-8*--
# Define class
class Class washing machine():
  # Definition__ init__ (). Add instance properties
  def __init__(self,wide,high):
      #Add instance properties,
      self.wide=wide
      self.high=high
  def Print information(self):
      #Class to call instance properties
      print(self.wide,self.high)

# create object
 Haier=Class washing machine(500,300)
Hisense=Class washing machine(400,500)
# verification
 Haier.Print information()
Hisense.Print information()

4.2 str(): generally returns some explanatory text

  • When using print to output the object name, the default memory address of the print object is not understood
 print(haier) #  Print out the memory address, indicating that the object is created successfully
 => <__main__.Class washing machine object at 0x0000000001241BA0>
  • If the class is defined__ str__ () method, it will return, explain the text of \ description, or explain the properties of the class, or the state of the class

    • code
 # --*coding:utf-8*--
# Define class
class Class washing machine():
   def __init__(self,wide,high):
       self.wide=wide
   def __str__(self):
       return (f"Here are the instructions")
Haier=Class washing machine(500,300)
print(Haier)
=>Here are the instructions

4.3 del():

When an object is deleted, Python automatically calls the del method

V. comprehensive application

Object oriented general steps

1 analyze requirements

   Time spent   ===>  Sweet potato state

2 step analysis

     Upper classification     Sweet potato 

2.1 defining classes (properties and methods)

  2.1.1 Basic properties initialization properties __init__(self):
  2.1.2 method  /function  def Function name():
  2.1.3 display information/return state   __str__(self):

2.2 create objects, test instance properties and instance methods

5.1 roasted sweet potato

Scenario Description:
Roast sweet potatoes. Take them out for a while. If they are not cooked, bake them inside. Take a look later and add up
Time and status

5.1. 1 demand

Demand main line:
1 baking time and corresponding state
0-5 minutes raw
Cooked in 5-10 minutes
More than 10 minutes
2 add seasoning:

5.1. 2 step analysis

The requirement involves one thing: sweet potato -- > classified on the sweet potato category

5.1. 2.1 definition class

Object oriented general steps

1 analyze requirements

   Time spent   ===>  Sweet potato state

2 step analysis

     Upper classification     Sweet potato 

2.1 defining classes (properties and methods)

  2.1.1 Basic properties initialization properties __init__(self):
  2.1.2 method  /function  def Function name():
  2.1.3 display information/return state   __str__(self):

2.2 create objects, test instance properties and instance methods

# --*coding:utf-8*--
"""
[Analysis requirements]
1\According to the time of roasting sweet potato ,Judging the state of sweet potato by cumulative time
2\According to the seasoning added,Output the taste of sweet potato

[Step analysis]
1\Define class initialization properties and methods/Function output status information
2\create object, Test instance properties and instance methods

"""
# 1 \ definition class
class Sweet potato():
    # Initialize properties
    def __init__(self):
        self.time=0
        self.state="raw"
        self.taste=[]
    # Instance method / function
    def Roasted sweet potatoes(self,time):
        self.time+=time
        if 0<=self.time<5:self.state="raw"
        elif 5<=self.time<10:self.state="Ripe"
        elif 10<=10:self.state="It's burnt"
    def Add seasoning(self,Seasoning):
        self.taste.append(Seasoning)
    def __str__(self):
        return f"Roasted sweet potato{self.time},{self.state},taste{self.taste}"
# create object
 Red sweet potato=Sweet potato()
print(Red sweet potato)  #Object sweet potato roasted 0, raw, taste []
Red sweet potato.Roasted sweet potatoes(7)
print(Red sweet potato)  #Object sweet potato roasted 7, cooked, taste []
Red sweet potato.Add seasoning("Brown sugar")
print(Red sweet potato)   # Object sweet potato is roasted 7, cooked and tastes ['brown sugar']

5.2 moving furniture

5.2. 1 demand

Put furniture smaller than the remaining area of the house into the house

5.2. 2 step analysis

House furniture

5.2. 2.1 definition class
  • House class
    – init() initialize attribute location floor area remaining area
    – def () calculate the remaining area and compare whether it can be put down
    – str() return is it OK to put it down
  • Furniture
    – init () initialization area
    Key problem: cross class parameter passing item
5.2. 2.2 create instance objects and verify instance properties and methods
#--*coding=utf-8*--
"""
[demand]  Move furniture smaller than the remaining area of the house into the house
 step
1\ Define class, House and furniture initialization properties
2\method/function  ①Judge the remaining area ②Judge whether it can be put down
3\create object,Verify instance properties and methods
"""
# Define class
class Furniture():
    def __init__(self,Furniture name,Furniture area):
        self.Furniture name=Furniture name
        self.Furniture area=Furniture area

class House class():
    def __init__(self,position,area covered):
        self.position=position
        self.area covered=area covered
        self.Remaining area=area covered
        self.Furniture list=[]
    def Move furniture(self,item):
        if self.Remaining area>=item.Furniture area:
            self.Furniture list.append(item.Furniture name)
            self.Remaining area-=item.Furniture area

        else:print("I can't hold it")
    def __str__(self):
        return f"be located{self.position}My house,Land occupation{self.area covered},surplus{self.Remaining area},Existing furniture{self.Furniture list}"
# create object
 Bed=Furniture("Double bed",6)
Table=Furniture("table",3)

Dongcheng 102=House class("12 Chang'an Street",140)
print(Dongcheng 102)
Dongcheng 102.Move furniture(Bed)
print(Dongcheng 102)
Dongcheng 102.Move furniture(Table)
print(Dongcheng 102)

Vi. summary object oriented

  • component
    – class
    class name ()
    code
    – object
    Object name = class name ()

  • Add object properties
    – inside the class
    self. Attribute name = value
    – outside the class
    Object name Attribute name = value

  • Get object properties
    – inside the class
    self. Attribute name
    – outside the class
    Object name Attribute name

  • Magic method

       __init__()  :Initialize properties
       __str__()  :Return object information,state
       __del__()  :Call to delete object
    

Keywords: Python Back-end

Added by Koobazaur on Wed, 15 Dec 2021 06:33:17 +0200