["stupid method" learning Python] 40. Modules, classes and objects OOP

Posted by shameermp on Thu, 30 Dec 2021 23:32:38 +0100

40. Modules, classes and objects - OOP

preface

   Python is an "object-oriented programming language (OOP)". This statement means that Python has a structure called class, through which software can be constructed in a special way. Using classes can enhance the consistency of programs and make them cleaner to use.

1. The module (module) is almost the same as the dictionary.

A dictionary is a way of mapping one thing to another. This means that if there is a dictionary, there is a key called 'apple' in it, and the way to get the value from it is:

mystuff = dict(apple="I AM APPLES!")
print(mystuff["apple"])

c this is a very important concept of "getting X from Y". Now let's look at some attributes of the module:
(1) A module is a Python file that contains functions and variables
(2) You can import this file
(3) You can then use "." Operators access functions and variables in modules
  you can define one named mystuff Py module, and there is a function called apple.

# this goes in mystuff.py
def apple():
    print("I AM APPLES!")

# this is just a variable
tangerine = "Living reflection of a dream."

  next, you can use import to call the module and access the function and its variables.

import mystuff as mys

mys.apple()
print(mys.tangerine)

  returning to the concept of dictionary, you will find that the calling method is somewhat similar to the use method of dictionary, but the syntax is different.

mystuff["apple"] 	# get apple from dict
mys.apple()			# get apple from the module
mys.tangerine		# some things, it's just a variable 

   in other words, there is a very common pattern in Python:
(1) A container similar to the "key = value" style
(2) Get the value from the name of the key
   for a dictionary, a key is a string, and the syntax for obtaining a value is "[key]"; for a module, key is the name of a function or variable, and the syntax is ". Key", which is the difference between a dictionary and a module.

2, Classes are similar to modules

   the module can be regarded as a special dictionary, through which some Python code can be stored, and through "." Operator. Python also has another code structure to achieve a similar purpose, that is, class. Through the class, you can put a set of functions and data into a container, so as to use "." Operator to access them.
  if you create a class by creating a mystuff module, the method is roughly as follows:

class MyStuff(object):
    def __init__(self):
        self.tangerine = "And now a thousand years between."
        
    def apple(self):
        print("I AM CLASSY APPLES!")

  this code is almost simulating a mini module called MyStuff, which has a function called apple. Among them, the most difficult to understand is__ init__ () function, as well as the self tangerine.
  the reason for using classes instead of modules is that many MyStuff classes can be created repeatedly, and they will not interfere with each other. For the module, after one import, the whole program has only this content, and new tricks can be made only when it is very deep.
  before understanding this, you must first know what the object is and how to use MyStuff to achieve something similar to MyStuff Py module effect.

3, Objects are similar to import s

  if a class is similar to a mini module, there must be a concept similar to import for a class. This concept is called "instantiation". This is just a pretentious name. It actually means "create". When a class is "instantiated", the result is called an object.
  the method of instantiating a class (creating a class) is to call a class like a function.

class MyStuff(object):
    def __init__(self):
        self.tangerine = "And now a thousand years between."
        
    def apple(self,message):
        print("I AM CLASSY APPLES!",message)


thing = MyStuff()         		# Instantiation operation
thing.apple("I LOVE YOU!")
thing.tangerine

  running the program will get:

  thing = MyStuff() is the "instantiation" operation, which is very similar to calling a function. Python does a series of work during instantiation:
(1) Python looks up MyStuff() and knows that it is a defined class
(2) Python creates an empty object that contains all the functions specified by def in the class
(3) Then Python returns to check whether it has created a__ init__ () if the "magic" function is created, it will call this function to initialize the newly created empty object
(4) On MyStuff__ init__ In the function, there is a redundant function called self, which is an empty object created by Python. You can operate on it like modules and dictionaries, and set some variables for it.
(5) self.tangerine = "And now a thousand years between." Set self The tangerine setting sets up a string, which initializes the object
(6) Finally, Python assigns the new object to a variable called thing for later use.

4, Get what is contained in something

  there are three ways to get something from something:

# dict style
mystuff["apple"]

# module style
mys.apple()
mys.tangerine

# class style
thing = MyStuff()
thing.apple("I LOVE YOU!")
thing.tangerine

5, Example of the first class

1. Atom text editor

class Song(object):

    def __init__(self, lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)

happy_bday = Song(["Happy birtday to you",
               "I don't want to get sued",
               "So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family",
                        "With pockets full of shells"])

happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()

2. Running a Python program

You can see the result by typing Python in Window.

python ex40.py

3. Practice

class People(object):
    
    # Construction method (magic method), a function that is automatically executed when an object is created
    def __init__(self, name, age, gender):
        # Bind an object to its properties
        self.name = name
        self.age = age           
        self.gender = gender    # attribute
     
    # Method (the function defined in the class is called method)
    def huijia(self):
        print("%s,%s,%s,Drop out and go home"%(self.name,self.age,self.gender))
    
    def quxufu(self):
         print("%s,%s,%s,Drive to pick up your daughter-in-law"%(self.name,self.age,self.gender))
    
    def kanchai(self):
         print("%s,%s,%s,Go up the mountain to cut firewood"%(self.name,self.age,self.gender))

#Create object (instantiation)
zhangsan = People("Zhang San", "18", "male")
lisi = People("Li Si", "35", "male" )
wangwu = People("Wang Wu", "45", "male")

zhangsan.huijia()
lisi.quxufu()
wangwu.kanchai()

summary

   the above content introduces the modules, classes and objects of Python. Articles on python, data science and artificial intelligence will be published from time to time. Please pay more attention and connect three times with one key (● '◡' ●).

Topics: Python