The basic syntax of Python based on machine learning (2)

      Disclaimer: The running environment of the code is Python3. Python3 and Python2 will be different in some details, I hope readers will pay attention. This blog is mainly code, and there will be detailed comments in the code. Related articles will be published in my personal blog column "Python from entry to deep learning" , welcome everyone to pay attention.


content

1. The basic syntax of Python based on machine learning (1)

2. The basic syntax of Python based on machine learning (2)

Third, the use of the Numpy library based on machine learning


       Through the first lecture above, I believe that everyone has a basic understanding of Python. Let's start our second lecture: the basic language of Python (2) on the basis of machine learning.


【Code】

'''
The basic syntax of Python based on machine learning 02
'''

# Function: The function code block starts with the def keyword, and the function content starts with a colon and is indented. The first line of the function statement can be a string, which is used for the function description.
# return [expression] Ends the function, an expression without a return value is equivalent to returning None
# grammar:
# def functionname(parameters):
# "function_docstring"
#     function_suite
#     return [expression]
def printme(s):
    '''
    print incoming string
    :stop s:
    :return:
    '''
    print(s)
    return s
printme('abc')

# Argument passing: For immutable types: C++-like value passing, such as integers, strings, tuples. Such as fun(a), only the value of a is passed, and it does not affect the a object itself.
# For example, modifying the value of a inside fun(a) only modifies another copied object, and will not affect a itself.
def ChangeInt(a):
    a = 10
b = 2
ChangeInt(b)
print(b) # The result is 2
# For mutable types: C++-like pass-by-reference, such as lists, dictionaries. For example, fun(list) means that the list is actually passed, and the list outside the fun will also be affected after the modification.
def changeme(mylist):
    mylist.append(50)
    print(mylist)
    return
mylist = [10, 20, 30]
changeme(mylist)
print(mylist)
#Everything in python is an object, strictly speaking, we can't say pass by value or pass by reference, we should say pass immutable objects and pass mutable objects

# Assign parameters by parameter name
def printinfo(name, age):
    print("Name: ", name)
    print("Age ", age)
    return
printinfo(age=22, name="xzw")

# default parameters
def printinfo(name, age=35):
    print("Name: ", name)
    print("Age ", age)
    return


printinfo(age=50, name="miki")
printinfo("miki")

# variable length parameter
def printinfo(arg1, *vartuple):
    print("Output: ")
    print(arg1)
    for x in vartuple:
        print(x)
    return
printinfo(10)
printinfo(20, 30, 40, 50)

# lambda function: lambda is just an expression, and the function body is much simpler than def; the lambda body is an expression, not a code block, and can only encapsulate limited logic in a lambda expression;
# lambda functions have their own namespace and cannot access parameters outside of their own parameter list or in the global namespace; Python only uses lambda
# Positioned as a short function for auxiliary use, so lambda can only write one line, can not assign values, can not be defined internally, etc.
sum = lambda arg1, arg2: arg1 + arg2
print(sum(10, 20))
def makeSum():
    sum = lambda arg1, arg2: arg1 + arg2
    return sum
f = makeSum()
print(f(10, 20))

# return value
def sum(arg1, arg2):
    total = arg1 + arg2
    print("Inside the function: ", total)
    return total
total = sum(10, 20)
print("Outside the function: ", total)

# function type parameters
def add(x, y, f):
    return f(x) + f(y)
print(abs(-3)) # absolute value
print(add(-3, 5, abs)) # When a function is used as a parameter, you cannot add ()

# Global variables and local variables: Variables defined inside a function have a local scope, and variables defined outside a function have a global scope. Local variables can only be accessed within the function in which they are declared, while global variables can be accessed program-wide.
total = 0 # this is a global variable
def sum(arg1, arg2):
    # total = arg1 + arg2; #Note the difference after the annotation is canceled here, if there is a variable with the same name, the local variable has a higher priority than the global variable
    print(total)
    return total
sum(10, 20)
print(total)

# global: Define the variable in the function as a global variable, you can change the value of the variable inside the function by defining it as a global variable
# globvar = 0 #The definition of globvar here is optional
def set_globvar_to_one():
    global globvar # use global to declare global variables
    globvar = 1
def print_globvar():
    print(globvar) # global is not used
set_globvar_to_one()
print(globvar) # prints 1
print_globvar() # output 1, the globvar in the function is already a global variable

# Module: Python module (Module), is a Python file, ending with .py, containing Python object definitions and Python statement modules so that you can logically organize your Python, code segments
# Distributing related code into a module makes your code more usable and easier to understand. Modules can define functions, classes and variables, and modules can also contain executable code
# support.py
# support module
def print_func(s):
    print("Hello : ", s)
    return
# hello.py
# # method one
# import support
#
# support.print_func("Tom")
#
# # Method 2
# from support import print_func
#
# print_func("Tom")
#
# # Method 3
# from support import *
#
# print_func("Tom")

# input and type conversion
import sys
# enter a string
# s=sys.stdin.readline() # Manual input
# print(s) #There will be an extra character '\n' at the end of the input string, for example, if the input is 'abc', the result is 'abc\n', so the length will be increased by 1
s = '100'
a = int(s)
b = float(a)
b += 1
s = str(b)
print(s)

# Namespaces and scopes: Variables are names (identifiers) with matching objects. A namespace is a dictionary containing variable names (keys) and their respective objects (values).
# A Python expression can access variables in both the local namespace and the global namespace. If a local variable and a global variable have the same name, the local variable overrides the global variable.
# Each function has its own namespace. The scope of a class method is the same as that of a normal function.

# Package: A package is a hierarchical file directory structure that defines a Python application environment consisting of modules, subpackages, and subpackages under subpackages. Simply put, a package is a folder, and the folder must exist
# __init__.py file, its content can be empty, __int__.py is used to identify the current folder as a package. The directory structure is as follows:
# hello.py
# mypackage(folder)
# | -- __init__.py
# | -- runoob1.py
# | -- runoob2.py
#
# runoob1.py:
# def f1():
#     print("I'm in runoob1")
#
# runoob2.py
# def f2():
#     print("I'm in runoob2")
# hello.py:
# from mypackage.runoob1 import f1
# from mypackage.runoob2 import f2
#
# f1 ()
# f2()
#
# import sys
#
# s = sys.stdin.readline()
# print(s)

# Exception handling: BaseException: base class for all exceptions
try:
    print(1 / 0)
except IOError:
    print("IOError")
except ZeroDivisionError:
    print("ZeroDivisionError")
else: # when there is no exception
    print("esle")
finally:
    print("finally")

# Class: The class method must contain the parameter self, and it is the first parameter
class Employee:
    'Base class for all employees' # The first line can be described as a string

    # empCount is a class variable, shared among all instances of this class, accessed using Employee.empCount
    empCount = 0

    # Constructor
    # self represents an instance of the class, which must be present when it is defined, and does not have to be passed when calling
    # Parameters are properties
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1

    def displayCount(self): # self cannot be omitted
        print("Total Employee %d" % Employee.empCount)

    def displayEmployee(self):
        print("Name : ", self.name, ", Salary: ", self.salary)


a = Employee("zhangsan", 5000)
print(Employee.empCount, a.name, a.salary)
a.age = 26 # add properties
print(a.age)
del a.age # delete attribute
# print(a.age)

b = Employee("lisi", 5000)
print(Employee.empCount, b.name, b.salary)
b.displayCount()
b.salary = 6000
b.displayEmployee()
print(b)

# About self: self represents an instance of the class, representing the address of the current object, and runoob.__class__ points to the class. self is not a keyword, you can replace it with others, such as: runoob
class Test:
    def myprint(runoob):
        print(runoob)
        print(runoob.__class__)
t = Test()
t.myprint()

# Built-in class properties
# __doc__: The docstring of the class
# __name__: class name
# __module__: The module where the class is defined (the full name of the class is
# '__main__.className', if the class is in an imported module mymodule, then __module__ is
# mymodule)
# __bases__: All parent class constituent elements of the class (contains a tuple consisting of all parent classes)
# __dict__: attributes of the class (contains a dictionary consisting of the data attributes of the class)
class Employee:
    'employee class'
    empCount = 0
print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)

# python object destruction (garbage collection): Python uses the simple technique of reference counting to track and collect garbage. Internally, Python keeps track of how many references to all objects in use,
# When an object is created, a reference count is created, and when the object is no longer needed, that is, when the object's reference count becomes 0, it is garbage collected. But recycling is not "immediately"
# The memory space occupied by garbage objects is reclaimed by the interpreter at an appropriate time. Such as:
a = 40 # create object <40>
b = a # Increment reference, count of <40>
c = [b] # Increment reference. <40> count
del a # decrement the count of references <40>
b = 100 # decrement the count of references <40>
c[0] = -1 # decrement the count of references <40>

# Destructor: The destructor __del__ is called when the object is destroyed
class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __del__(self):
        class_name = self.__class__.__name__
        print(class_name, "destroy")
pt1 = Point()
pt2 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3)) # print the id of the object
of pt1
of pt2
of pt3

# Inheritance: The base class constructor (__init__()) will not be called automatically. Python first looks for the called method in this class, and then goes to the base class if it cannot find it. If more than one is listed in the inheritance tuple class, then it is called "multiple inheritance"
class Parent: # Parent class
    parentAttr = 100

    def __init__(self):
        print("Call the parent class constructor")

    def parentMethod(self):
        print('Call the parent class method')

    def setAttr(self, attr):
        Parent.parentAttr = attr

    def getAttr(self):
        print("Parent class attribute:", Parent.parentAttr)

class A:
    a = 0

class Child(Parent, A): # subclass, multiple inheritance
    def __init__(self):
        print("Call the subclass constructor")

    def childMethod(self):
        print('Call the subclass method')

c = Child() # instantiate the child class
c.childMethod() # call the method of the subclass
c.parentMethod() # call the parent class method
c.setAttr(200) # Call the method of the parent class again - set the attribute value
c.getAttr() # Call the method of the parent class again - get the attribute value

# method override
class Parent: # Define the parent class
    def myMethod(self):
        print('Call the parent class method')

class Child(Parent): # define a subclass
    def myMethod(self):
        print('Call the subclass method')

c = Child() # child class instance
c.myMethod() # The subclass calls the overridden method

# Operator overloading: Note: Python does not support function overloading.
# Common overloaded methods:
# Method        	Overloads        	Call for
# ------          ----------          ---------
# __init__ constructor X=Class()
# __del__ destructor object destruction
# __add__        	+                	X+Y,X+=Y
# __sub__ -XY,X-=Y
# __or__        	|                	X|Y,X|=Y
# __repr__ print conversion print X, repr(X)
# __str__ print conversion print X, str(X)
# __call__ call function X()
# __getattr_ limit X.undefine
# __setattr__ value X.any=value
# __getitem__ index X[key],
# __len__ length len(X)
# __cmp__        	比较            	X==Y,X<Y
# __lt__        	小于            	X<Y
# __eq__ is equal to X=Y
# __radd__        Right-Side +        	+X
# __iadd__ + = X + = Y
# __iter__ iteration For In

# plus overload
class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

    def __add__(self, other):
        return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2, 10)
v2 = Vector(6, 1)
print(v1 + v2)

# minus sign overload
class Number:
    def __init__(self, start):
        self.data = start # add attributes

    def __sub__(self, other):  # minus method
        return Number(self.data - other)

number = Number(30)
y = number - 10
print(y.data)  # 20

# Private: Private attributes: start with two underscores, cannot be used outside the class, use self.__XXX when used inside the class. But you can use object._className__attrName to access private attributes
# Private methods: start with two underscores, cannot be called outside the class, use self.__private_methods when calling inside the class
class JustCounter:
    __secretCount = 0 # private variable
    publicCount = 0 # public variable

    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print(self.__secretCount)

counter = JustCounter()
counter.count()
print(counter.publicCount)
# print(counter.__secretCount) #error
print(counter._JustCounter__secretCount)

# Description of single underline, double underline, head and tail double underline:
# 1. __XXX__: defines special methods, such as __init__()
# 2. _foo: A variable that starts with a single underscore indicates a protected type variable.
# That is, the protected type can only allow itself and subclasses to be accessed, and cannot be used for from module import *
# 3. __foo: Double underscores indicate variables of private type, which can only be accessed by the class itself

What problems did you encounter in this process, welcome to leave a message, let me see what problems you have encountered.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325986322&siteId=291194637