Python foundation super detailed notes -- object oriented Foundation

Object oriented Foundation

target

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

1, Understanding object orientation

Object oriented is an abstract programming idea, which is common in many programming languages.

For example: washing clothes

Thinking: how many ways can you finish washing clothes?

Answer: hand wash and machine wash.

Hand washing: find a basin - Drain - add washing powder - soak - Scrub - wring dry water - pour water - rinse N times - wring dry - air.

Machine washing: turn on the washing machine - put the clothes - add washing powder - press the start button - dry.

Thinking: comparing the two ways of washing clothes, what did the students find?

A: machine washing is simpler

Thinking: for machine washing, you only need to find a washing machine and add simple operation to complete the washing work, without caring about what happened inside the washing machine.

Conclusion: object oriented is to treat programming as a thing. For the outside world, things are used directly, regardless of their internal situation. Programming is to set what things can do.

2, Classes and objects

Thinking: in the description process of washing clothes, the washing machine is actually a thing, that is, the object. Where does the object of the washing machine come from?

A: washing machines are made by factory workers.

Thinking: how do factory workers make washing machines?

A: workers make washing machines according to the functional drawings designed by designers.

Summary: drawing → washing machine → washing clothes.

In the process of object-oriented programming, there are two important components: classes and objects.

Relationship between class and object: use class to create an object.

2.1 understanding classes and objects

Type 2.1.1

Class is a general term for a series of things with the same characteristics and behavior. It is an abstract concept, not a real thing.

  • Characteristics are attributes
  • Behavior is method

Classes, for example, are drawings used in the manufacture of washing machines, that is, classes are used to create objects.

2.1.2 object

Objects are real things created by classes, such as washing machines.

Note: in development, there are classes before objects.

2.2 object oriented implementation method

2.2.1 definition class

There are two classes in Python 2: Classic class and new class

  • grammar
class Class name():
    code
    ......

Note: the class name shall meet the identifier naming rules and follow the naming habit of big hump.

  • experience
class Washer():
    def wash(self):
        print('I can wash clothes')
  • Expansion: Classic

A class that does not derive from any built-in type is called a classic class

class Class name:
    code
    ......

2.2.2 creating objects

Object, also known as instance.

  • grammar
Object name = Class name()
  • experience
# create object
haier1 = Washer()

# <__main__.Washer object at 0x0000018B7B224240>
print(haier1)

# The haier object calls the instance method
haier1.wash()

Note: the process of creating an object is also called instantiating an object.

2.2.3 self

self refers to the object that calls the function.

# 1. Definition class
class Washer():
    def wash(self):
        print('I can wash clothes')
        # <__main__.Washer object at 0x0000024BA2B34240>
        print(self)


# 2. Create object
haier1 = Washer()
# <__main__.Washer object at 0x0000018B7B224240>
print(haier1)
# haier1 object calls instance method
haier1.wash()


haier2 = Washer()
# <__main__.Washer object at 0x0000022005857EF0>
print(haier2)

Note: the results obtained by printing the object and self are consistent, both of which are the memory address of the current object.

3, Add and get object properties

Attributes are features, such as the width, height, weight of the washing machine

Object properties can be added and obtained either outside the class or inside the class.

3.1 adding object attributes outside class

  • grammar
Object name.Attribute name = value
  • experience
haier1.width = 500
haier1.height = 800

3.2 get object attributes outside class

  • grammar
Object name.Attribute name
  • experience
print(f'haier1 What is the width of the washing machine{haier1.width}')
print(f'haier1 What is the height of the washing machine{haier1.height}')

3.3 get object properties in class

  • grammar
self.Attribute name
  • experience
# Define class
class Washer():
    def print_info(self):
        # Class to get instance properties
        print(f'haier1 What is the width of the washing machine{self.width}')
        print(f'haier1 What is the height of the washing machine{self.height}')

# create object
haier1 = Washer()

# Add instance properties
haier1.width = 500
haier1.height = 800

haier1.print_info()

4, Magic method

In Python__ xx__ The function of () is called magic method, which refers to the function with special function.

4.1 __init__()

4.1.1 experience__ init__ ()

Thinking: the width and height of the washing machine are inherent attributes. Can these attributes be given in the production process?

A: it should be.

__ init__ () method: initializes an object.

class Washer():
    
    # Functions that define initialization functions
    def __init__(self):
        # Add instance properties
        self.width = 500
        self.height = 800


    def print_info(self):
        # Class to call instance properties
        print(f'What is the width of the washing machine{self.width}, Height is{self.height}')


haier1 = Washer()
haier1.print_info()

be careful:

  • __ init__ () method is called by default when creating an object and does not need to be called manually
  • __ init__ The self parameter in (self) does not need to be passed by the developer. The python interpreter will automatically pass the current object reference.

4.1.2 with parameters__ init__ ()

Thinking: a class can create multiple objects. How to set different initialization properties for different objects?

Answer: pass parameters.

class Washer():
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def print_info(self):
        print(f'What is the width of the washing machine{self.width}')
        print(f'What is the height of the washing machine{self.height}')


haier1 = Washer(10, 20)
haier1.print_info()


haier2 = Washer(30, 40)
haier2.print_info()

4.2 __str__()

When using print to output an object, the memory address of the object is printed by default. If the class is defined__ str__ Method, the data return ed from this method will be printed.

class Washer():
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def __str__(self):
        return 'This is the instruction manual of Haier washing machine'


haier1 = Washer(10, 20)
# This is the instruction manual of Haier washing machine
print(haier1)

4.3 __del__()

When an object is deleted, the python interpreter also calls by default__ del__ () method.

class Washer():
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def __del__(self):
        print(f'{self}The object has been deleted')


haier1 = Washer(10, 20)

# <__ main__. Washer object at 0x000002618223278 > object has been deleted
del haier1

5, Comprehensive application

5.1 roasted sweet potato

5.1.1 requirements

Demand main line:

  1. Roasted time and corresponding sweet potato state:

    0-3 minutes: raw

    3-5 minutes: half cooked

    5-8 minutes: cooked

    More than 8 minutes: burnt

  2. Seasoning added:

    Users can add spices according to their wishes

5.1.2 step analysis

The demand involves a thing: sweet potato, so the case involves a class: sweet potato.

5.1.2.1 definition class

  • Properties of sweet potato

    • Baking time
    • State of sweet potato
    • Seasoning added
  • Method for producing sweet potato

    • Roasted
      • The user sets the time for each roast of sweet potato according to their wishes
      • Judge the total baking time of sweet potato and modify the state of sweet potato
    • Add seasoning
      • You can set the seasoning to be added according to your wishes
      • Store the seasoning added by the user
  • Display object information

5.1.2.2 create objects and call relevant instance methods

5.1.3 code implementation

5.1.3.1 definition class

  • Sweet potato attribute
    • Define the initialization attribute of sweet potato, and update the instance attribute according to the program in the later stage
class SweetPotato():
    def __init__(self):
        # Baking time
        self.cook_time = 0
        # State of sweet potato
        self.cook_static = 'raw'
        # Seasoning list
        self.condiments = []

5.1.3.2 define the method of roasting sweet potato

class SweetPotato():
    ......
    
    def cook(self, time):
        """Method for roasting sweet potato"""
        self.cook_time += time
        if 0 <= self.cook_time < 3:
            self.cook_static = 'raw'
        elif 3 <= self.cook_time < 5:
            self.cook_static = 'halfcooked'
        elif 5 <= self.cook_time < 8:
            self.cook_static = 'Ripe'
        elif self.cook_time >= 8:
            self.cook_static = 'It's burnt'

5.1.3.3 write str magic method, which is used to output object status

class SweetPotato():
		......

    def __str__(self):
        return f'This sweet potato is roasted{self.cook_time}minute, Status is{self.cook_static}'

5.1.3.4 create objects, test instance properties and instance methods

digua1 = SweetPotato()
print(digua1)
digua1.cook(2)
print(digua1)

5.1.3.5 define the method of adding seasoning and call the instance method

class SweetPotato():
		......

    def add_condiments(self, condiment):
        """Add seasoning"""
        self.condiments.append(condiment)
    def __str__(self):
        return f'This sweet potato is roasted{self.cook_time}minute, Status is{self.cook_static}, The spices added are{self.condiments}'
      

digua1 = SweetPotato()
print(digua1)

digua1.cook(2)
digua1.add_condiments('soy sauce')
print(digua1)

digua1.cook(2)
digua1.add_condiments('chili powder')
print(digua1)

digua1.cook(2)
print(digua1)

digua1.cook(2)
print(digua1)

5.1.4 code overview

# Define class
class SweetPotato():
    def __init__(self):
        # Baking time
        self.cook_time = 0
        # State of sweet potato
        self.cook_static = 'raw'
        # Seasoning list
        self.condiments = []

    def cook(self, time):
        """Method for roasting sweet potato"""
        self.cook_time += time
        if 0 <= self.cook_time < 3:
            self.cook_static = 'raw'
        elif 3 <= self.cook_time < 5:
            self.cook_static = 'halfcooked'
        elif 5 <= self.cook_time < 8:
            self.cook_static = 'Ripe'
        elif self.cook_time >= 8:
            self.cook_static = 'It's burnt'

    def add_condiments(self, condiment):
        """Add seasoning"""
        self.condiments.append(condiment)

    def __str__(self):
        return f'This sweet potato is roasted{self.cook_time}minute, Status is{self.cook_static}, The spices added are{self.condiments}'


digua1 = SweetPotato()
print(digua1)

digua1.cook(2)
digua1.add_condiments('soy sauce')
print(digua1)

digua1.cook(2)
digua1.add_condiments('chili powder')
print(digua1)

digua1.cook(2)
print(digua1)

digua1.cook(2)
print(digua1)

5.2 moving furniture

5.2.1 requirements

Place furniture smaller than the remaining area of the house in the house

5.2.2 step analysis

Demand involves two things: house and furniture, so the case involves two categories: house and furniture.

5.2.2.1 definition class

  • House class

    • Instance properties
      • House location
      • Floor area of the house
      • Remaining area of house
      • List of furniture in the house
    • Example method
      • Accommodating furniture
    • Display house information
  • Furniture

    • Furniture name
    • Furniture floor area

5.2.2.2 create objects and call related methods

5.2.3 code implementation

5.2.3.1 definition class

  • Furniture
class Furniture():
    def __init__(self, name, area):
        # Furniture name
        self.name = name
        # Furniture floor area
        self.area = area
  • House class

class Home():
    def __init__(self, address, area):
        # geographical position
        self.address = address
        # House area
        self.area = area
        # Remaining area
        self.free_area = area
        # Furniture list
        self.furniture = []

    def __str__(self):
        return f'The house is located in{self.address}, area covered{self.area}, Remaining area{self.free_area}, Furniture has{self.furniture}'

    def add_furniture(self, item):
        """Accommodating furniture"""
        if self.free_area >= item.area:
            self.furniture.append(item.name)
            # After the furniture is moved in, the remaining area of the house = the previous remaining area - the area of the furniture
            self.free_area -= item.area
        else:
            print('The furniture is too large and the remaining area is insufficient to accommodate')

5.2.3.2 create objects and call instance properties and methods

bed = Furniture('Double bed', 6)
jia1 = Home('Beijing', 1200)
print(jia1)

jia1.add_furniture(bed)
print(jia1)

sofa = Furniture('sofa', 10)
jia1.add_furniture(sofa)
print(jia1)

ball = Furniture('Basketball Court', 1500)
jia1.add_furniture(ball)
print(jia1)

6, Summary

  • An important part of object-oriented

    • class
      • Create class
    class Class name():
      code
    
    • object
    Object name = Class name()
    
  • Add object properties

    • Outside class
    Object name.Attribute name = value
    
    • Inside the class
    self.Attribute name = value
    
  • Get object properties

    • Outside class
    Object name.Attribute name
    
    • Inside the class
    self.Attribute name
    
  • Magic method

    • __ init__ (): initialization
    • __ str__ (): output object information
    • __ del__ (): called when an object is deleted

Keywords: Python

Added by djlfreak on Tue, 23 Nov 2021 05:59:57 +0200