Python3.8 Basic syntax reading such as official website documents

  • 2021-11-29 07:43:36
  • OfStack

Directory 1, Class Definition 2, Class Object 3, Instance Object 4, Method Object 5, Class and Instance Variable 6, Supplementary Notes

Basic Grammar Reading of Official Website Class

English official document: https://docs.python.org/3. 8/tutorial/classes.html

Official Chinese document: https://docs.python.org/zh-cn/3. 8/tutorial/classes.html

Class provides a way to combine data and functionality.

Creating 1 new class means creating 1 新的对象类型 Which allows 1 new instance of the type to be created.

1. Class definition

The simplest class definition looks like this:


class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>

Class definition and function definition (def statement) 1 must be executed to be effective.

When you enter the class definition, a new namespace is created and used as a local scope. Therefore, all assignments to local variables are within this new namespace. In particular, the function definition is bound to the new function name here.

2. Class objects

Class objects support two operations: attribute reference and instantiation.

(1) Attribute reference

Standard syntax for attribute references: obj.name .

Valid property names are all names that exist in the class namespace when the class object is created. Therefore, if the class definition is like this:


class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

Then MyClass.i And MyClass.f Is a valid property reference, which will return 1 integer and 1 function object respectively.

Class properties can also be assigned, so they can be changed by assignment MyClass.i The value of.

__doc__ Is also a valid property that returns the document string of the class to which it belongs: "A simple example class".

(2) Instantiation

Class is instantiated using functional notation.

You can think of a class object as a function without parameters that returns a new instance of the class. For example (assuming the above class is used):


x = MyClass()

Create a new instance of the class and assign this object to the local variable x.

Instantiating the operation ("calling" the class object) creates an empty object, or you can use the __init__() Create a custom instance with a specific initial state. For example:


def __init__(self):
    self.data = []

At this point, the instantiation operation of the class is automatically called for the newly created class instance __init__() . Therefore, in this example, you can pass the x = MyClass() Statement to get a new initialized instance:

__init__() Methods can also have additional parameters for greater flexibility. In this case, the parameters supplied to the class instantiation operator are passed to the __init__() . For example:


>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

3. Instance object

The only operation of an instance object is a property reference. There are two valid property names: data property and method.

(1) Data attributes

Data attributes do not need to be declared, like local variable 1, they will be generated the first time they are assigned.

For example, if x is an instance of the MyClass created above, the following code snippet will print the value 16 without retaining any trace information:


x.counter = 1
while x.counter < 10:
    x.counter = x.counter * 2
print(x.counter)
del x.counter

(2) Methods

Method is a function that is "subordinate" to an object. [Note: Methods are for objects, functions are for classes]

(In Python, the term method is not specific to class instances: Other objects can have methods. For example, list objects have methods such as append, insert, remove, sort, etc. However, in the following discussion, we use the term Method 1 to refer exclusively to the methods of class instance objects, unless explicitly stated otherwise.)

The valid method name of an instance object depends on the class to which it belongs. [Note: This is the name of the method]

By definition, all the properties of a class that are function objects are the corresponding methods that define their instances.

So in our example, x. f is a valid method reference because MyClass. f is a function and x. i is not a method because MyClass. i is not a function. But x. f is not the same thing as MyClass. f, it is a method object, not a function object.

4. Method objects

Typically, methods are called immediately after binding, which in the MyClass example returns the string 'hello world'.

x.f()

However, it is not necessary to call a method immediately: x. f is a method object that can be saved and called later. For example:


xf = x.f
while True:
    print(xf())

Printing hello world continues until the end.

Although f() The function definition of specifies 1 parameter, but it is called above x.f() There is no parameter when. Python certainly throws an exception when calling a function that requires arguments without arguments, even if the arguments are not actually used.

Method is special in that the instance object is passed in as the first parameter of the function. In our example, calling x. f () is equivalent to MyClass. f (x). "Note: This is self in the method parameter list"

In a word, calling a method with n parameters is equivalent to calling the corresponding function with one more parameter, which is the instance object to which the method belongs, before other parameters.

When the non-data attribute "Note: Method" of an instance is referenced, the class to which the instance belongs will be searched.

If the referenced property name represents a function object in a valid class property, the method object is created by packaging (pointing) the found instance object and function object into an abstract object: this abstract object is the method object. [Note: xf = x. f, x. f is a method object]

When a method object is called with a parameter list, a new parameter list is built based on the instance object and the parameter list [Note: self and the parameter list], and the corresponding function object is called using this new parameter list.

5. Class and instance variables

In general, instance variables are used for only 1 data per instance, while class variables are used for properties and methods shared by all instances of a class:

"Note: In the following example kind Is a class variable, name Is an instance variable "


class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs
'canine'
>>> e.kind                  # shared by all dogs
'canine'
>>> d.name                  # unique to d
'Fido'
>>> e.name                  # unique to e
'Buddy'

As discussed in Names and Objects shared data can lead to surprising results when it comes to mutable objects such as lists and dictionaries.

For example, the tricks list in the following code should not be used as a class variable, because all Dog instances will only share a single list:

"Note: Class variables are shared by all instances. The tricks list in the following code should not be used as a class variable. When the instance calls add_trick, it changes the tricks list."


class Dog:

    tricks = []             # mistaken use of a class variable

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

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks                # unexpectedly shared by all dogs
['roll over', 'play dead']

Proper class design should use instance variables:


class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']

6. Supplementary explanations

If the same property name appears in both an instance and a class, the property lookup takes precedence over the instance:


class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
0

The first parameter of the method is often named self. This is just a convention: the name self has absolutely no special meaning in Python. Note, however, that not following this convention will make your code less readable to other Python programmers, and it is conceivable that a browser-like program might be written in reliance on this convention.

Any function that is a class attribute defines a corresponding method for an instance of the class. The text of the function definition does not have to be included in the class definition: it is also possible to assign a function object to a local variable. For example:


class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
1

Now f, g, and h are all properties of reference function objects of the C class, so they are all methods of instances of C, where h is exactly equivalent to g. However, please note that the approach of this example usually only confuses the reader of the program.

Method can call other methods by using the method property of the self parameter:


class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
2

Method can refer to global names in the same way as ordinary functions. The global scope associated with a method is the module that contains its definition. (Classes are never treated as global scopes.)

Although there is rarely a good reason to use global scope in a method, there are many legitimate usage scenarios for global scope: for example, functions and modules imported into global scope can be used by a method, as can functions and classes defined in it.

Typically, the class containing the method itself is defined in global scope, and in the next section we will find a good reason why the method needs to refer to the class to which it belongs.

Each value is 1 object, so it has a class (also known as a type) and is stored as object.__class__ .


Related articles: