Introduction to python for beginners - functions, classes, modules, packages

Keywords: Python Pycharm

14. Function

def calc(a ,b):'''establish'''
    c=a-b
    return c;


calc1 = calc(10, 20)'''call'''
calc2 =calc(b=50,a=60)
print(calc1)
print(calc2)


In the process of function call, parameters are passed
If it is an immutable object, the modification of the function body will not affect the value of the argument. The modification of arg1 to 100 will not affect the value of n1
If it is a variable object, the modification of the function body will affect the value of the argument arg2, and the modification of append(10) will affect the value of n2
Return value of function
(1) If the function has no return value [after the function is executed, you do not need to provide data to the caller] return can be omitted

(2) The return value of the function. If it is 1, it returns the type directly
(3) The return value of the function. If there are multiple, the returned result is a tuple

You can view print

print(self, *args, sep=' ', end='\n', file=None)

end Default Wrap

  • Variable number of position parameters
def p(*args):
    print(args)
    #print(args[0]) #Used as a tuple
    
p(20,20,30)
p(20)
lst=[10,20,30]
p(*lst) #When a function is called, each element in the list is converted into a position argument
#(20, 20, 30)
#(20,)
#(10, 20, 30)

#eg: 
print(self, *args, sep=' ', end='\n', file=None)
Position parameters
  • Variable number of keyword parameters
def fun(** args):
    print(args)
    
fun(a=10)
fun(a=20,b=30,c=60)
dic={'a':111,'b':222,'c':333}
fun(**dic)#When the function is called, the key value pairs in the dictionary are converted into keyword arguments
#{'a': 10}
#{'a': 20, 'b': 30, 'c': 60}
#{'a': 111, 'b': 222, 'c': 333}

For the above two variable parameters, a function can only define one

When two are used at the same time, the variable number of location parameters is required to precede the variable number of keyword parameters

All three methods are OK if * is not added

15. Category

1) Create syntax

class Student:
    pass
print(id(Student)) #Space has been opened up
print(type(Student))
print(Student)
'''
2450633353136
<class 'type'>
<class '__main__.Student'>
'''

The function defined in the class is

2) Instance call

There will be a class pointer to the class in the created instance object

  • Object name. Method name
  • Class name. Method name (class object) # is self at the definition

  • Class properties

  • Class method

Class methods and static calls:

Studet.cm() #cls does not need to be passed in
Studet.method()

3) Dynamic binding properties and methods

python is a dynamic language. After creating an object, you can dynamically bind properties and methods

  • Dynamic binding properties
    eg: add an attribute to the object
class Student:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def eat(self):
        print(self.name+'be at  table')

stu1=Student('Zhang San',20)
stu1.gender='female'
print(stu1.gender,stu1.name,stu1.age)
  • Dynamic binding method
class Student:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def eat(self):
        print(self.name+'be at  table')
def show():
    print("Methods defined outside a class are called methods")
stu1.s=show()
stu1.s

4) Encapsulation, inheritance, polymorphism

  • python does not have a modifier to identify the private of a property. You can use two_

Only the internal can be accessed, but not the external

(by programmers)

  • Inherit object class by default

    class Animal(object):
    

    The following parentheses write the parent class

    When a subclass and a parent have methods with the same name, the subclass overrides the parent

    • Judge whether a variable is a type and parent inheritance chain
	isinstance(c, Dog) #Similar to Java
  • Opening and closing principle

    • Open to expansion

      You can add a new subclass, inherit the parent class, and override the methods of the parent class

    • Closed for modification

      You cannot modify methods that depend on the type of the parent class (the parent type is used as the incoming parameter)

16. Module

Files ending in. py can be used as modules

Module in package

  • code reuse
  • Division of labor and cooperative development
  • Avoid duplicate naming

  • Common built-in modules
    • sys
    • time
    • os
    • calendar (standard library of date related functions)
    • urllib (read the data standard library of the server)
    • json
    • re
    • math
    • decimal
    • logging
  • Import third party packages

17. Package

Packages in Python

  • Package is a hierarchical directory structure, which organizes a group of modules with similar functions

  • effect

Code specification
Avoid module name conflicts·

  • Difference between package and directory
    Contain__ init_ . The directory of Py files is called package directory, which usually does not contain_ init_.py file
    heart

  • Import of packages
    import package name. Module name as alias

  • Use from... Import to import packages, modules, functions and variables

Built in function

1.isinstance

Sometimes it can replace type()

Determine whether it is an object of a class

Determine whether it is an object of one of multiple classes

isinstance('a', str)

isinstance([1, 2, 3], (list, tuple))
True
isinstance((1, 2, 3), (list, tuple))
True

2.dir()

Get all the properties and methods of an object

>>> dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']
#__ add__   Named for special purposes, such as__ len__ Method return length
>>> hasattr(obj, 'x') # Is there an attribute (method and variable) 'x'?
True
>>> obj.x
9
>>> hasattr(obj, 'y') # Is there an attribute 'y'?
False
>>> setattr(obj, 'y', 19) # Set a property 'y'
>>> hasattr(obj, 'y') # Is there an attribute 'y'?
True
>>> getattr(obj, 'y') # Get property 'y'
19
>>> obj.y # Get property 'y'
19

Posted by markmusicman on Fri, 15 Oct 2021 20:48:19 -0700