In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "how to understand object-oriented programming in Python". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to understand object-oriented programming in Python.
Python supports many types of programming paradigms, such as procedural programming, functional programming, object-oriented programming, and can integrate many types of paradigms.
Nowadays, object-oriented programming is widely used. The basic element of object-oriented programming is an object, which contains data members called attributes and functions (routines, procedures) called methods.
Object is an instance of a class. In other words, the class mainly defines the structure of the object, and then we use the class as a template to create the object. Class contains not only method definitions, but also data shared by all instances.
There are many other aspects of object-oriented programming in Python. I hope this article can provide a good start for you to learn Python and implement object-oriented.
Create a Python class
We can use the keyword class to define the Python class, followed by the class name, semicolon, and class implementation:
> class MyClass:... Pass...
By convention, the Python class is named in uppercase (that is, PascalCase).
Now let's create an instance of this new class called MyClass:
> a = MyClass () > a
The statement a = MyClass () creates an instance of MyClass and assigns its reference to the variable a.
We can get the type (that is, the class of the object) through the built-in function type () of Python or directly through the property. _ _ class__. After getting the class (type), we can use the attribute. _ _ name__ to get the name of the class:
> > type (a)
> a. Classrooms classrooms _
> a.classrooms classically located. Classically assigned _
'MyClass'
By the way, Python classes are also objects. They are examples of type:
> type (MyClass)
Next, let's define a method.
The first parameter of each instance method in Python must correspond to the instance, that is, the object itself. By convention, this parameter is called self. This is followed by other parameters (if necessary). When calling a method, we do not need to explicitly provide parameters corresponding to the parameter self.
Usually, one of the most important methods we need to define is. _ init__ (). This method is called after an instance of the class is created. This method is responsible for initializing class members. We define. _ _ init__ () as follows:
> class MyClass:... Def _ _ init__ (self, arg_1, arg_2, arg_3):... Print (f'an instance of {type (self). _ _ name__} created'). Print (f'arg_1: {arg_1}, arg_2: {arg_2}, arg_3: {arg_3}')..
Next, let's create an instance of MyClass and see how this initialization method works. Our. _ init__ () method takes three parameters (arg_1, arg_2, and arg_3), so remember that we don't need to pass the first parameter corresponding to self. So, when we instantiate an object, we need to pass three parameters:
> a = MyClass (2,4,8)
An instance of MyClass created
Arg_1: 2, arg_2: 4, arg_3: 8
The results of the above statement are as follows:
Create an instance of an object of type MyClass.
Automatically calls the instance's method. _ _ init__ ().
The parameters we passed to the MyClass () method: (2J4 and 8) are passed to. _ init__ ().
. _ _ init__ () executes our request and outputs the result. It uses type (self). _ _ name__ to get the name of the class.
Now we have a class that has a method. _ _ init__ (), and an instance of this class.
Data attribute
Let's modify MyClass to add some data attributes.
We initialize and define the instance with. _ _ init__ (), and we can also change the property value by assigning a value to a data property in this method or other instance methods:
> class MyClass:
... Def _ _ init__ (self, arg_1, arg_2, arg_3):
... Self.x = arg_1
... Self._y = arg_2
... Self.__z = arg_3
...
MyClass now has three data properties:
.x can get the value of arg_1
. _ y can get the value of arg_2
. _ z can get the value of arg_3
We can use Python's unpacking mechanism to write this code in a more compact form:
> class MyClass:
... Def _ _ init__ (self, arg_1, arg_2, arg_3):
... Self.x, self._y, self.__z = arg_1, arg_2, arg_3
...
The underscore (_) in the attribute name indicates that these attributes are "private" attributes:
Attributes that are not underlined at the beginning (such as .x) are usually available for invocation and modification outside the object.
Properties that begin with an underscore (such as. _ y) can also be called and modified from outside the object. However, underlining is a commonly used flag, that is, the creators of this class strongly recommend that this variable not be used. The variable should be called and modified only through functional members of the class, such as methods and properties.
An attribute that begins with a double underscore (such as. _ z) will be renamed during the name modification process (in this case it will be renamed. _ MyClass__z). You can also call and modify them from outside the object with this new name. However, I strongly object to this approach. Calls and modifications should be made through the functional members of the class with their original names.
The data properties of a Python object are usually stored in a dictionary called. _ _ dict__, which is also one of the properties of the object. However, you can also store data properties elsewhere. We can visit _ _ dict__, directly or use Python's built-in function vars () to get. _ _ dict__:
> a = MyClass (2,4,8) > > vars (a) {'xchocolate: 2,' _ MyClass__z':: 4,'_ MyClass__z': 8} > > a.
The name modification process changes the key'_ z'to'_ MyClass__z''.
We can use. _ _ dict__ as an ordinary Python dictionary.
The general ways to get and modify the values associated with data properties are as follows:
> > a.x2 > > a._y4 > a.__zTraceback (most recent call last): File "", line 1, in AttributeError: 'MyClass' object has no attribute' _ z' > > a.x = 16 > > a.x16 > vars (a) {'x: 16,'_ MyClass__z':: 4,'_ MyClass__z': 8}
Note that we cannot access. _ z because. _ _ dict__ does not have the key'_ _ z'.
Example method
Next, let's create two instance methods:
● .set _ z (): modify. _ z.
●. Get _ z (): returns the value of. _ z.
Remember that the first parameter of each instance method (named self according to the convention) refers to the object itself, but we do not need to specify this parameter when the method is called:
> class MyClass:
... Def _ _ init__ (self, arg_1, arg_2, arg_3):
... Self.x, self._y, self.__z = arg_1, arg_2, arg_3
...
... Def set_z (self, value):
... Self.__z = value
...
... Def get_z (self):
... Return self.__z
...
> b = MyClass (2,4,8)
The methods .get _ z () and .set _ z () provide traditional ways to retrieve and modify the. _ z value:
> b.get_z () 8 > b.set_z (16) > vars (b) {'xmom: 2,' _ MyClass__z': 16}
You can also add other functions to .get _ z () and .set _ z (), such as checking the validity of the data. This approach implements a major concept in object-oriented programming: encapsulation.
Attribute
Another way (a more Python way) to access and modify data properties is to use properties. Properties encapsulate a series of methods: getter, setter, and deleter, but behave the same as normal data properties.
The following code implements the property .z, which also includes the functions of .get _ z () and .set _ z ():
> class MyClass:
... Def _ _ init__ (self, arg_1, arg_2, arg_3):
... Self.x, self._y, self.__z = arg_1, arg_2, arg_3
...
... @ property
... Def z (self):
... Return self.__z
...
... @ z.setter
... Def z (self, value):
... Self.__z = value
...
> b = MyClass (2,4,8)
As follows, we use the corresponding attribute .z to access and modify the data attribute. _ z:
> b.z8 > b.z = 16 > vars (b) {'xchocolate: 2,' _ MyClass__z':: 4,'_ MyClass__z': 16}
This code is more concise and elegant than the example above.
Classes and static methods
In addition to instance methods and properties, a class can have class methods and static methods.
Let's add three methods for MyClass:
> class MyClass:
... Def _ _ init__ (self, arg_1, arg_2, arg_3):
... Self.x, self._y, self.__z = arg_1, arg_2, arg_3
...
... Def f (self, arg):
... Print ('instance method f called')
... Print (f'instance: {self}')
... Print (f'instance attributes:
{vars (self)}')
... Print (f'class: {type (self)}')
... Print (f'arg: {arg}')
...
... @ classmethod
... Def g (cls, arg):
... Print ('class method g called')
... Print (f'cls: {cls}')
... Print (f'arg: {arg}')
...
... @ staticmethod
... Def h (arg):
... Print ('static method h called')
... Print (f'arg: {arg}')
...
> c = MyClass (2,4,8)
The method .f () is an instance method. The first parameter of the instance method is a reference to the object itself. These methods can use self to access the object, vars (self) or self.__dict__ to access the object's data properties, and type (self) or self.__class__ to access the corresponding class of the object, and they can have their own parameters.
The beginning of the method .g () contains the modifier @ classmethod, indicating that this is a class method. The first parameter of each class method points to the class itself, which by convention is named cls. As in the case of the example method, we do not need to explicitly provide parameters corresponding to the cls. Class methods can access the class itself with cls and its own parameters.
The beginning of the method .h () contains the modifier @ staticmethod, indicating that this is a static method. Static methods can only access their own parameters.
The common methods to call instance methods in Python are as follows:
> c.f ('my-argument') instance method f calledinstance: instance attributes: {' xboys: 2,'_ MyClass__z':: 4,'_ MyClass__z': 8} class: arg: my-argument
In general, we should call class and static methods directly through the class (not the instance):
> MyClass.g ('my-argument') class method g calledcls: arg: my-argument > MyClass.h (' my-argument') static method h calledarg: my-argument
Remember, we don't need to pass the first parameter of the class method: the parameter corresponding to cls.
However, we can call class methods and static methods as follows:
> c.g ('my-argument') class method g calledcls: arg: my-argument > c.h (' my-argument') static method h calledarg: my-argument
When we call c.g or c.h, but the instance member does not have such a name, Python searches for class and static members.
Inherit
Inheritance is another important feature of object-oriented programming. In this concept, a class (called a subclass or derived class) inherits data and function members from other classes (called a superclass or base class).
In Python, all classes inherit class objects that come with Python by default. However, we can define an appropriate class inheritance hierarchy as needed.
For example, we can create a new class called MyOtherClass, which inherits MyClass:
Class MyOtherClass (MyClass):... Def _ init__ (self, u, v, w, x, y, z):. Super (). _ _ init__ (x, y, z)... Self.__u, self.__v, self.__w = u, v, w. ... Def f _ (self, arg):... Print ('instance method f _ called'). Print (f'instance: {self}'). Print (f'instance attributes: {vars (self)}'). Print (f'class: {type (self)}'). Print (f'arg: {arg}')... > > d = MyOtherClass (1,2,4,8,16,32)
As mentioned above, MyOtherClass has members of MyClass: .x, .y, .z, and .f (). You can initialize the data members x,. _ y, and. _ z of the base class with the statement super (). _ _ init__ (x, y, z), which calls the base class's. _ init__ () method.
In addition, MyOtherClass has its own members:. _ u,. _ v,. _ w and. F _ ().
Next, we get the data members through vars ():
> vars (d) {'x MyOtherClass__v':: 8,'_ MyOtherClass__w':: 16,'_ MyClass__z': 32,'_ MyOtherClass__u': 1,'_ MyOtherClass__v': 2,'_ MyOtherClass__w': 4}
We can call all the methods in the base and derived classes:
> > d. F ('some-argument') instance method f calledinstance: instance attributes: {' x: 8,'_ y: 16,'_ MyClass__z': 32,'_ MyOtherClass__u': 1,'_ MyOtherClass__v': 2,'_ MyOtherClass__w': 4} class: arg: some-argument > > d _ f _ ('some-argument') instance method f _ calledinstance: instance attributes: {' x: 8,'_ y: 16,'_ MyClass__z': 32 '_ MyOtherClass__u': 1,' _ MyOtherClass__v': 2,'_ MyOtherClass__w': 4} class: arg: some-argument
However, if a derived class contains a member with the same name as the base class, the member of the derived class takes precedence.
At this point, I believe you have a deeper understanding of "how to understand object-oriented programming in Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.