Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the concept of Python

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the concept of Python". In daily operation, I believe many people have doubts about what the concept of Python is. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what is the concept of Python?" Next, please follow the editor to study!

Object

Objects play a central role in Python. Let's take a look at how to deepen our understanding of the subject.

Under the hood

You probably know the built-in len function. It returns the length of the object you gave it. But what is the length of the number five? Let's ask Python:

> > len (5)

Traceback (most recent call last): File "", line 1, inTypeError: object of type 'int' has no len ()

I like mistakes because they show how Python works internally. In this case, Python tells us that 5 is an object and that there is no len ().

In Python, everything is an object. Strings, Boolean values, numbers and even functions are all objects.

We can use the built-in function dir () to examine the objects in REPL. When we try dir on the number 5, it displays a large list of functions contained in any numeric object:

> > dir (5)

['_ _ abs__','_ _ add__','_ _ and__','_ _ bool__','_ _ ceil__','_ _ class__',...'_ _ str__','_ _ sub__','_ _ subclasshook__','_ truediv__','_ trunc__','_ xor__', 'bit_length',' conjugate', 'denominator' 'from_bytes', 'imag',' numerator', 'real',' to_bytes']

I omitted some of the list for the sake of clarity.

The list begins with these strangely underlined named functions, such as _ _ add__. These methods are called magic methods or dunder (abbreviation for double underscores) methods.

If you look closely, you will see that objects of type int do not have a _ _ len__ dunder method. This is how the len () function of Python knows that numbers have no length. All len () does is call the _ _ len _ () method on the object that provides it. This is why Python complains that objects of type "int" do not have len ().

I casually introduce the word method here. Let me define it more formally:

When a function is part of an object, we call it a method.

So, if a string does have a length, it must have a _ _ len__ method, right? Find out!

> dir ("test")

['_ _ add__','_ _ class__','__contains__','_ _ delattr__','_ _ dir__','_ _ doc__','_ _ eq__','_ _ format__','_ _ ge__','_ _ getattribute__','_ _ getitem__','_ getnewargs__','_ _ gt__','_ _ hash__' '_ _ init__',' _ _ init_subclass__','_ _ iter__','_ _ le__','_ _ len__','_ _ lt__','_ _ mod__','_ _ mul__','_ _ ne__','_ _ new__','_ reduce__','_ reduce_ex__','_ repr__','_ _ rmod__' '_ rmul__',' _ setattr__','_ sizeof__','_ str__','_ subclasshook__', 'capitalize',' casefold', 'center',' count', 'encode',' endswith', 'expandtabs',' find', 'format',' format_map', 'index',' isalnum', 'isalpha',' isascii', 'isdecimal',' isdigit', 'isidentifier' 'islower', 'isnumeric',' isprintable', 'isspace',' istitle', 'isupper',' join', 'ljust',' lower', 'lstrip',' maketrans', 'partition',' replace', 'rfind',' rindex', 'rjust',' rpartition', 'rsplit',' rstrip', 'split',' splitlines', 'startswith',' strip', 'swapcase',' title', 'translate' 'upper',' zfill']

Yes, there. Because this is a method, we can also call it:

> "test". _ _ len__ ()

four

This is equivalent to len ("test"), but not elegant enough. So don't do this, just to show how these things work.

Dir () also shows us some other less magical methods. Feel free to try something, such as islower:

> > "test" .islower ()

True

This method checks whether the entire string is lowercase, so Python returns a Boolean value of True. Some of these methods require one or more parameters, such as replace:

> 'abcd'.replace (' averse,'b')

'bbcd'

It replaces all occurrences of "a" with "b".

What is the object?

Now that we've used objects and know that everything in Python is objects, it's time to define what objects are:

An object is a collection of data (variables) and methods for manipulating that data

Object and object-oriented programming were popular concepts in the early 1990s. Early computer languages like C had no concept of objects. However, it turns out that objects are examples that are easy for humans to understand-they can be used to model many realities.

Today, most, if not all, new languages have the concept of objects. Therefore, what you are about to learn will conceptually apply to other languages as well.

Because objects are the foundation of the Python language, it is logical that you can also create objects yourself. To do this, we need to define a class first.

Class

If you want to create your own object type, you first need to define the methods it has and the data it can hold. This blueprint is called a class.

A class is a blueprint for an object

All objects are based on one class. When you create an object, we call it "creating an instance of the class." Strings, numbers and even Boolean values are instances of a class. Let's explore the built-in function types:

> type ('a')

> > type (1)

Type (True)

Obviously, there are some classes called str,int and bool. These are some of Python's native classes, but we can also build our own classes!

If there is no car analogy, then no tutorial is complete, so let's create a class that represents the car. There is a lot of input, and you have to restart each error. Try anytime, but if you want to take shortcuts, I understand. Simply copy and paste the following into your Python REPL:

Class Car: speed = 0 started = False def start (self): self.started = True print ("Car started, let's ride!") Def increase_speed (self, delta): if self.started: self.speed = self.speed + delta print ('Vroooooomorphic') Else: print ("You need to start the car first") def stop (self): self.speed = 0 print ('Halting')

Don't worry, we'll walk through it step by step, but first create and use objects of type Car:

> > car = Car ()

> > car.increase_speed (10)

You need to start the car first

> > car.start ()

Car started, let's ride!

Car.increase_speed (40)

Vrooooom!

> _

An object is always an instance of a class. There can be many instances in one category. We just created an instance of the Car class using Car () and assigned it to the variable car. Creating an instance is like calling a function-you'll see why later.

Next, we call up a method for the car object: try to increase its speed before it starts. Oh, no! Only after starting the car can we increase the speed and enjoy the noise it makes.

Now, let's take a look at the car lesson step by step:

Use the class statement followed by the class name (Car) to define the class. Let's indent the code block starting with the colon.

We define two variables, speed and start. This is the data that all instances of this class will have.

Next, we define three ways to manipulate variables.

In the definition of these methods, we encounter some strange things: they all have a parameter named self as their first parameter.

What is Self?

To be honest, if you ask me, this is one of the less elegant language constructs of Python.

Remember when we called methods on the car object, such as car.start ()? Even if start is defined as a start (self) in a class, we don't have to pass the self variable.

This is what is happening:

When we call a method on an object, Python automatically populates the first variable, which we used to call self

The first variable is a reference to the object itself, so its name

We can use this variable to reference other instance variables and functions of the object, such as self.speed and self.start ().

Therefore, it is only within the class definition that we use self to reference variables that belong to the instance. To modify the start variables that are part of our course, we use self.started instead of just starting it.

By using self, we can clearly see the variables we are working on on this instance, rather than other variables that are defined outside the object and happen to have the same name.

Create multiple objects from a class

Because a class is just a blueprint, you can use it to create multiple objects, just as you can create multiple cars with the same appearance. They all behave similarly, but they all have their own data, which is not shared between objects:

> > car1 = Car ()

> > car2 = Car ()

> id (car1)

139771129539104

> id (car2)

139771129539160

Here we create two car objects, car1 and car2, and use the built-in method id () to get their id. Each object in Python has a unique identifier, so we just prove that we created two different objects from the same class. We can use them independently:

> > car1.start ()

Car started, let's ride!

> > car1.increase_speed (10)

'Vrooommom'

> car1.speed

ten

> car2.speed

0

We just started car1 and increased the speed, while car2 is still paused. Check the speed to confirm that this is a different car in different states!

Constructor function

When we create an object from a class, it looks like we are calling a function:

Car = Car ()

But it doesn't just look like we're calling a function, it's actually calling a function! This method that we do not have to define is called a constructor. It constructs and initializes objects. By default, each class has a class named _ _ init__, even if we don't define it ourselves. This is about inheritance, which you will soon learn.

Have you ever used the str () function to convert an object to a class? Or does the int () function convert a string to a number?

>'a' + str (1)

'a1'

> int ('2') + 2

four

What you're actually doing here is creating new objects of types str and int by calling the constructors of the str and int classes.

We can also override the _ _ init__ method to give it more functionality by accepting parameters. Let's redefine the Car class using a custom constructor:

Class Car: def _ init__ (self, started = False, speed = 0): self.started = started self.speed = speed def start (self): self.started = True print ("Car started, let's ride!") Def increase_speed (self, delta): if self.started: self.speed = self.speed + delta print ("Vrooooom!") Else: print ("You need to start the car first") def stop (self): self.speed = 0

Our custom constructor has named parameters with default values, so we can create instances of the Car class in a number of ways:

> C1 = Car ()

> c2 = Car (True)

> c3 = Car (True, 50)

> c4 = Car (started=True, speed=40)

You may have noticed that we can now create new cars that are not started but still need to increase speed. Now, let's do this.

Inherit

In programming, it is best to reuse as much code as possible. It even has a good acronym called DRY: don't repeat yourself.

Classes can help you avoid duplicating code, because you can write a class once and create many objects based on it. However, they also help you in another way, called inheritance. Classes can inherit properties and functions from other classes, so you don't have to repeat your work.

For example, we want the Car class to inherit some of the basics of the Vehicle class. And, at the same time, the Motorcycle class is defined. From the diagram, it looks like this:

> Inheritance-image by author

We have seen inheritance at work. Remember when I told you that even if you didn't define a class, each class had an init? This is because each class inherits from the most basic class in Python, namely object:

> dir (object)

['_ _ class__','_ _ delattr__','_ _ dir__','_ _ doc__','_ _ eq__','_ _ format__','_ _ ge__','_ _ getattribute__','_ _ gt__','_ _ hash__','_ init__','_ init_subclass__','_ _ le__','_ _ lt__' '_ _ ne__',' _ _ new__','_ _ reduce__','_ _ reduce_ex__','_ _ repr__','_ _ setattr__','_ sizeof__','_ _ str__','_ _ subclasshook__']

When I tell you that "everything in Python is an object," I mean everything. This includes classes, and you can see that we can also use dir () on classes. It indicates that the object has a _ _ init__ method. Not bad, isn't it?

Inheritance maps to many realities. According to the figure above, let's look at the role of inheritance. We will start with the generic Vehicle class:

Class Vehicle: def _ init__ (self, started = False, speed = 0): self.started = started self.speed = speed def start (self): self.started = True print ("Started, let's ride!") Def stop (self): self.speed = 0 def increase_speed (self, delta): if self.started: self.speed = self.speed + delta print ("Vrooooom!") Else: print ("You need to start me first")

Now we can redefine our Car class using inheritance:

Class Car (Vehicle): trunk_open = False def open_trunk (self): trunk_open = True def close_trunk (self): trunk_open = False

Our car inherits all the methods and variables of the Vehicle class, but adds an additional variable and two methods to manipulate the trunk.

Override init method

Sometimes you want to override the init function. To demonstrate, we can create a Motorcycle class. Most motorcycles have a central bracket. We will add the ability to place or initialize it:

Class Motorcycle (Vehicle): def _ init__ (self, center_stand_out = False): self.center_stand_out = center_stand_out super (). _ _ init__ ()

When you override the constructor, the constructor of the parent class (from which we inherit) is not called at all. If you still need this feature, you must call it yourself. This is done through super (): it returns a reference to the parent class, so we can call the constructor of the parent class.

In this case, we added the mid-bracket function, but removed the option to set the speed and startup state in the constructor. If desired, you can also add speed and startup status options and pass them to the Vehicle constructor.

Override other methods

Just like _ _ init__, we can override other methods. For example, if you want to implement a motorcycle that does not start, you can override the startup method:

Class Motorcycle (Vehicle): def _ init__ (self, center_stand_out = False): self.center_stand_out = center_stand_out super (). _ init__ () def start (self): print ("Sorry, out of fuel!") At this point, the study of "what is the concept of Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report