Basic Grammar Reading for Official Classes
Official Documentation in English./3.8/tutorial/
Official Chinese Documentation./zh-cn/3.8/tutorial/
Classes provide a way to combine data and functionality.
Creating a new class means creating aNew object types
, thus allowing the creation of a new instance of that type.
1. Class Definition
The simplest class definition looks like this.
class ClassName: <statement-1> . . . <statement-N>
Class definitions, like function definitions (def statements), must be executed to have any effect.
When entering a 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, function definitions are bound to the new function name here.
2. Class Objects
Class objects support two operations: property referencing and instantiation.
(1) Attribute references
Standard syntax for attribute references.。
Valid attribute names are all the names that existed in the class namespace when the class object was created. Thus, if the class definition looks like this.
class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world'
in that case respond in singing
are just valid property references that will return an integer and a function object, respectively.
Class attributes can also be assigned values, so they can be changed by assigning the The value of the
__doc__
is also a valid attribute that will return the documentation string of the class: "A simple example class".
(2) Instantiation
Classes are instantiated using a function representation.
A class object can be thought of as a function that returns a new instance of that class without arguments. 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.
The instantiation operation ("calling" the class object) creates an empty object, or you can use the__init__()
Creates a custom instance with a specific initial state. Example.
def __init__(self): = []
At this point, the class instantiation operation is automatically called for the newly created instance of the class__init__()
. So in this example, thex = MyClass()
statement to get a new, initialized instance of.
__init__()
Methods can also have additional parameters for greater flexibility. In this case, the arguments provided to the class instantiation operator are passed to the__init__()
. For example:.
>>> class Complex: ... def __init__(self, realpart, imagpart): ... = realpart ... = imagpart ... >>> x = Complex(3.0, -4.5) >>> , (3.0, -4.5)
3. Instance objects
The only operation of an instance object is a property reference. There are two valid property names: data properties and methods.
(1) Data attributes
Data attributes do not need to be declared, like local variables they will be generated when they are first assigned.
For example, if x is an instance of MyClass created above, the following snippet will print the value 16 without any trace information.
= 1 while < 10: = * 2 print() del
(2) Methodology
Methods are functions "subordinate" to objects. [Note: Methods are object-specific, functions are class-specific.]
(In Python, the term method is not specific to class instances: other objects can have methods, too. For example, a list object has methods such as append, insert, remove, sort, and so on. However, in the following discussion, we use the term method to refer exclusively to the methods of class-instance objects, unless explicitly stated otherwise.)
Valid method names for instance objects depend on the class to which they belong. [Note: This is about method names.]
By definition, all attributes of a class that are function objects define the corresponding methods of their instances.
So in our example, it's a valid method reference because it's a function, and it's not a method because it's not a function. But it's not the same thing as being a method object, not a function object.
4. Method objects
Typically, the method is called immediately after binding, which in the MyClass example returns the string 'hello world'.
()
However, calling a method immediately is not required: it is a method object that can be saved and called later. Example.
xf = while True: print(xf())
will continue to print hello world until the end.
even thoughf()
function definition specifies a parameter, but in the above call to the()
with no arguments. Python will definitely raise an exception when calling a function that takes an argument without an argument, even if the argument is not actually used.
The special thing about methods is that the instance object is passed in as the first argument to the function. In our example, calling () is actually equivalent to (x). [Note: this is also known as self in the method argument list].
In summary, 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, positioned before the other parameters.
When a non-data attribute [note: i.e., method] of an instance is referenced, the class to which the instance belongs is searched.
If the referenced property name represents a function object within a valid class property, the method object is created by packing (pointing) the found instance and function objects to an abstract object: this abstract object is the method object. Note: xf = , is a method object.
When a method object is called with an attached argument list, a new argument list [note: self and argument list] is constructed based on the instance object and the argument list, and the corresponding function object is called using this new argument list.
5. Classes and instance variables
In general, instance variables are used for unique data for each instance, while class variables are used for properties and methods shared by all instances of the class:.
[Note: In the following examplekind
is a class variable.name
is an instance variable]
class Dog: kind = 'canine' # class variable shared by all instances def __init__(self, name): = name # instance variable unique to each instance >>> d = Dog('Fido') >>> e = Dog('Buddy') >>> # shared by all dogs 'canine' >>> # shared by all dogs 'canine' >>> # unique to d 'Fido' >>> # unique to e 'Buddy'
precisely asNames and objects As already discussed in , sharing data can lead to surprising results when it comes to mutable objects, such as lists and dictionaries.
For example, the list of tricks in the following code should not be used as a class variable, since all instances of Dog will share only a single list.
Note: Class variables are shared by all instances, the list of tricks in the following code should not be used as a class variable, the instance calls add_trick which changes the list of tricks.
class Dog: tricks = [] # mistaken use of a class variable def __init__(self, name): = name def add_trick(self, trick): (trick) >>> d = Dog('Fido') >>> e = Dog('Buddy') >>> d.add_trick('roll over') >>> e.add_trick('play dead') >>> # unexpectedly shared by all dogs ['roll over', 'play dead']
Proper class design should use instance variables: the
class Dog: def __init__(self, name): = name = [] # creates a new empty list for each dog def add_trick(self, trick): (trick) >>> d = Dog('Fido') >>> e = Dog('Buddy') >>> d.add_trick('roll over') >>> e.add_trick('play dead') >>> ['roll over'] >>> ['play dead']
6. Additional notes
If the same attribute name appears in both the instance and the class, the attribute lookup prioritizes the instance:.
>>> >>> class Warehouse: purpose = 'storage' region = 'west' >>> w1 = Warehouse() >>> print(, ) storage west >>> w2 = Warehouse() >>> = 'east' >>> print(, ) storage east
The first argument to a 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 makes your code unreadable to other Python programmers, and it's conceivable that a browser-like program could be written to depend on such a convention.
Any function that is an attribute of a class defines a corresponding method for instances of that class. The text of a function definition does not have to be contained within the class definition: it is possible to assign a function object to a local variable. Example.
# Function defined outside the class def f1(self, x, y): return min(x, x+y) class C: f = f1 def g(self): return 'hello world' h = g
Now f, g, and h are all attributes of a referenced function object of class C, and thus they are all methods of instances of C, with h being exactly equivalent to g. Note, however, that the approach of this example is usually only confusing to the reader of the program.
Methods can call other methods by using the method attribute of the self argument: the
class Bag: def __init__(self): = [] def add(self, x): (x) def addtwice(self, x): (x) (x)
Methods can refer to global names in the same way as normal functions. The global scope associated with a method is the module containing its definition. (Classes are never used as global scopes.)
Although we will rarely have a good reason to use global scopes in methods, there are many legitimate scenarios for their use: for example, functions and modules imported into global scopes can be used by methods, as can functions and classes defined within them.
Typically, the class containing the method is itself defined in the global scope, and in the next section we'll find good reasons why the method needs to reference the class it belongs to.
Each value is an object and therefore has a class (also known as a type) and is stored as aobject.__class__
。
to this article on Python3.8 official documents and other basic syntax to read the article is introduced to this, more related python3.8 basic syntax content please search my previous articles or continue to browse the following related articles I hope you will support me in the future more!