In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the example analysis of the basic grammar of Python3.8 class, which is very detailed and has certain reference value. Friends who are interested must finish it!
1. Class definition
The simplest class definition looks like this:
Class ClassName:. . .
A class definition, like a function definition (def statement), must be executed for it to work.
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 object
Class objects support two operations: property reference and instantiation.
(1) attribute reference
Standard syntax for property references: obj.name.
Valid attribute names are all names that exist in the class namespace when the class object is created. So, 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 are valid property references that return an integer and a function object, respectively.
Class properties can also be assigned, so you can change the value of MyClass.i by assigning values.
_ _ doc__ is also a valid property that returns the document string of the class to which it belongs: "A simple example class".
(2) instantiation
The instantiation of a class uses a functional representation.
You can think of a class object as a function that returns a new instance of the class without arguments. For example (suppose you use the above class):
X = MyClass ()
Create a new instance of the class and assign this object to the local variable x.
The instantiation operation (the invocation class object) creates an empty object, or you can use _ _ init__ () to create a custom instance with a specific initial state. For example:
Def _ init__ (self): self.data = []
At this point, the instantiation of the class automatically calls _ _ init__ () for the newly created class instance. So in this example, you can get a new initialized instance through the x = MyClass () statement:
The _ _ init__ () method can also have additional parameters for more flexibility. In this case, the parameters supplied to the class instantiation operator are passed to _ _ 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 properties and methods.
(1) data attributes
Data attributes do not need to be declared, and like local variables, they will be generated when they are assigned for the first time.
For example, if x is an instance of the MyClass created above, the following code snippet prints the value 16 and does not retain any tracking information:
X.counter = 1while x.counter
< 10: x.counter = x.counter * 2print(x.counter)del x.counter (2)方法 方法是"从属于"对象的函数。 【注:方法是针对对象来说的,函数是针对类来说的】 (在 Python 中,方法这个术语并不是类实例所特有的:其他对象也可以有方法。例如,列表对象具有 append, insert, remove, sort 等方法。然而,在以下讨论中,我们使用方法一词将专指类实例对象的方法,除非另外显式地说明。) 实例对象的有效方法名称依赖于其所属的类。 【注:这里说的是方法名称】 根据定义,一个类中所有是函数对象的属性都是定义了其实例的相应方法。 因此在我们的示例中,x.f 是有效的方法引用,因为 MyClass.f 是一个函数,而 x.i 不是方法,因为 MyClass.i 不是一个函数。 但是x.f 与 MyClass.f 并不是一回事,它是一个方法对象,不是函数对象。 4、方法对象 通常,方法在绑定后立即被调用,在 MyClass 示例中,这将返回字符串 'hello world'。 x.f() 但是,立即调用一个方法并不是必须的: x.f 是一个方法对象,它可以被保存起来以后再调用。 例如: xf = x.fwhile True: print(xf()) 将继续打印 hello world,直到结束。 虽然 f() 的函数定义指定了一个参数,但在上面调用 x.f() 时并没有带参数。 当不带参数地调用一个需要参数的函数时 Python 肯定会引发异常,即使参数实际未被使用。 方法的特殊之处就在于实例对象会作为函数的第一个参数被传入。 在我们的示例中,调用 x.f() 其实就相当于 MyClass.f(x)。 【注:也就是方法参数列表中的self】 总之,调用一个具有 n 个参数的方法就相当于调用再多一个参数的对应函数,这个参数值为方法所属实例对象,位置在其他参数之前。 当一个实例的非数据属性【注:即方法】被引用时,将搜索实例所属的类。 如果被引用的属性名称表示一个有效的类属性中的函数对象,会通过打包(指向)查找到的实例对象和函数对象 到一个抽象对象的方式来创建方法对象:这个抽象对象就是方法对象。 【注:xf = x.f,x.f 是一个方法对象】 当附带参数列表调用方法对象时,将基于实例对象和参数列表构建一个新的参数列表【注:self和参数列表】,并使用这个新参数列表调用相应的函数对象。 5、类和实例变量 一般来说,实例变量用于每个实例的唯一数据,而类变量用于类的所有实例共享的属性和方法: 【注:下例中kind是类变量,name是实例变量】 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 dumped Fidol'> e.name # unique to estrangement Buddha'
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 share only a single list:
[note: class variables are shared by all instances. The tricks list in the following code should not be used as class variables. When the instance calls add_trick, the tricks list is changed]
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']
The correct 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 notes
If the same property name appears in both the instance and the class, the property lookup takes precedence over the instance:
> class Warehouse: purpose = 'storage' region =' west' > W1 = Warehouse () > print (w1.purpose, w1.region) storage west > w2 = Warehouse () > w2.region = 'east' > print (w2.purpose, w2.region) storage east
The first parameter of 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 will make your code less readable to other Python programmers, and it is conceivable that the writing of a browser-like program may depend on such a 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:
# Function defined outside the classdef 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 properties of class C referencing function objects, so they are all methods of instances of C, where h is exactly equivalent to g. Note, however, that the approach of this example usually only confuses the reader of the program.
Methods can call other methods by using the method property of the self parameter:
Class Bag: def _ init__ (self): self.data = [] def add (self, x): self.data.append (x) def addtwice (self, x): self.add (x) self.add (x)
Method can reference a global name in the same way as a normal function. The global scope associated with a method is the module that contains its definition. Classes will never be used as a global scope. )
Although we rarely have a good reason to use a global scope in a method, there are many legitimate usage scenarios: for example, functions and modules imported into the global scope can be used by the method. the functions and classes defined in it are the same.
Typically, the class that contains the method itself is defined in the global scope, and in the next section we will find a good reason why the method needs to reference the class to which it belongs.
Each value is an object, so it has a class (also known as a type) and is stored as object.__class__.
The above is all the content of the article "sample Analysis of the basic Grammar of the Python3.8 Class". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.