From zero to Hero, a text mastering Python

Source: Internet
Author: User
Tags class definition instance method integer numbers

First question, what is Python? According to Python's father Guido van Rossum, Python is:

A high-level programming language whose core design philosophy is code readability and syntax that allows programmers to express their ideas with little code.

For me, the primary reason for learning Python is that Python is a language that can be programmed gracefully. It can simply and naturally write the code and implement my ideas.

Another reason is that we can use Python in many places: Data science, WEB development, and machine learning can all be developed using Python. Quora, Pinterest, and Spotify all use Python for their back-end Web development. So let's learn Python.

Python Basics 1. Variables

You can think of variables as a word to store values. Let's look at an example.

It is easy to define a variable in Python and assign it a value. If you want to store the number 1 to the variable "one", let's try it:

Super simple, huh? You only need to assign the value 1 to the variable "one".

As long as you want, you can assign any value to any other variable. As you can see from the above, the variable "one" stores the integer variable 2, and the variable "Some_number" stores 10000.

In addition to integral types, we can also use Boolean values (True/flase), strings, floating-point types, and other kinds of data.

# Booleanstrue_boolean = Truefalse_boolean = false# stringmy_name = "Leandro Tk" # floatbook_price = 15.80

2. Control Flow: Conditional statements

"If" uses an expression to determine whether a statement is true or False, and if true, executes the if code, as in the following example:

2:1 large, so the print code is executed.

When the expression inside the "if" is false, the "else" statement executes.

1:2 is small, so the code inside the "Else" is executed.

You can also use the "elif" statement:

3. Loops and Iterations

In Python, we can iterate in different forms. I'll say while and for.

While loop: When the statement is True, the code block inside the while is executed. So the code below will print 1 to 10.

The while loop requires a loop condition, and if the condition is always True, it will iterate until the value of NUM is 11 o'clock and the loop condition is false.

Another piece of code can help you better understand the use of the while statement:

The loop condition is True so it iterates until it is False.

For loop: You can apply the variable "num" on the code block, and the "for" statement will iterate over it for you. This code prints the same code as in while: from 1 to 10.

Did you see that? It's too easy. I range from 1 onwards to the 11th element (10 is the tenth element)

List: Collection | Arrays | Data

If you want to store integer 1 in a variable, but you also want to store 2 and 3, 4, 5 ...

Instead of using hundreds or thousands of variables, do I have a different way of storing the integers I want to store? As you've guessed, there are other ways to store them.

A list is a collection that can store a column of values (as you would like to store them), so let's use it:

It's really simple. We created an array called My_integer and stored the data inside.

Perhaps you would ask, "How do I get the values in the array?" ”

That's a good question. The list has a concept called indexing. The following table of the first element is index 0 (0). The second index is 1, and so on, you should understand.

To make it more concise, we can use its index to represent the array elements. I drew it out:

With Python's syntax, it's also good to understand:

If you don't want to deposit integers. You just want to save some strings, like a list of your relatives ' names. My looks are similar to this:

Its principle is the same as the storage of integers, very friendly.

We only learned how the index of a list works, and I need to tell you how to add an element to the data structure of a list (add an item to the list).

The most common way to add new data to a list is by stitching. Let's take a look at how it's used:

Stitching is super simple, you just need to put an element (such as "effective Machine") as the stitching parameter.

Well, the knowledge of the list is enough, let's take a look at the other data structures.

Dictionary: Key-value Data structure

Now we know that List is an integer numeric collection with indexes. But what if we don't use integer numbers as an index? We can use other data structures, such as numbers, strings, or other types of indexes.

Let's learn the data structure of the dictionary. A dictionary is a collection of key-value pairs. The dictionary is almost as long as this:

Key is the index that points to value. How do we access the value in the dictionary? You should have guessed that it was using key. Let's try it:

We have a key (age) value (24), which uses a string as the key integer as value.

I created a dictionary about me that contains my name, nickname, and nationality. These properties are key in the dictionary.

Just like we learned. Using an index to access a list, we also use the index (the key in the dictionary is the index) to access the value stored in the dictionary.

As we use list, let's learn how to add elements to a dictionary. The main point in the dictionary is the key to value. The same is true when we add elements:

We just need to point a key in a dictionary to a value. It's nothing difficult, is it?

Iteration: Looping through the data structure

As we learned in the Python Foundation, the List iteration is very simple. We Python developers typically use a for loop. Let's try it:

For each book on the bookshelf, we print (can do anything) to the console. Super simple and intuitive. This is the beauty of Python.

For a hash data structure, we can also use a for loop, but we need to use key to:

Above is an example of how to use a for loop in a dictionary. For each key in the dictionary, we print out the value corresponding to the key and key.

Another way is to use the Iteritems method.

We named two parameters as key and value, but this is not necessary. We can name it at will. Let's look at the following:

You can see that we use attribute as the key parameter in the dictionary, which has the same effect as using the key name. It's great!

Classes & Objects Some theories:

An object is a representation of a real-world entity, such as a car, dog, or bicycle. These objects have two common main characteristics: data and behavior.

Cars have data, such as the number of wheels, the number of doors and the space of seats, and they can show their behavior: they can accelerate, stop, show how much fuel is left, and many other things.

We consider data as attributes and behaviors in object-oriented programming. also expressed as:

Data → properties and behaviors → methods

A class is a blueprint for creating a single object. In the real world, we often find many objects of the same type. Cars, for example. All cars have the same structure and model (all have an engine, wheels, doors, etc.). Each vehicle is constructed from the same set of blueprints and has the same components.

Python Object-Oriented Programming mode: On

Python, as an object-oriented programming language, has such concepts as classes and objects.

A class is a blueprint, a model of an object.

Well, a class is a model, or a method of defining properties and behaviors (as we discussed in the theory section). For example, a vehicle class has its own properties to define what kind of vehicle the object is. The properties of a car are the number of wheels, the energy type, the seat capacity and the maximum speed of these.

With this in mind, let's look at the syntax of the Python class:

The above code, we use the class statement to define a class. Isn't it easy?

An object is an instantiation of a class, which we can instantiate by using the class name.

Here, car is the object (or instantiation) of the class Vehicle.

Remember the vehicle class has four properties: Number of wheels, tank type, seat capacity and maximum speed. When we create a new vehicle object, we want to set all the properties. So here we define a class that takes parameters when it is initialized:

This init method. We call this a constructor function. So when we create a vehicle object, we can define these properties. Imagine that we like Tesla Model S, so we want to create an object of this type. It has four wheels, which make electricity energy, five seats and a maximum speed of 250-kilometer (155 miles). Let's start creating an object like this:

Four wheel + electric energy + five seats + maximum speed 250-kilometer.

All the properties have been set. But how do we access these property values? We send a message to the object to request the value. We call it a method. It is the behavior of the object. Let's implement it:

This is the implementation of the two methods Number_of_wheels and Set_number_of_wheels. We call it a Getter & setter. Because the first function is to get the property value, the second function sets a new value for the property.

In Python, we can use @property (modifiers) to define getters and setters. Let's take a look at the actual code:

And we can use these methods as attributes:

This is slightly different from the method definition. The method here is performed according to the attributes. For example, when we set a new tyre number, we do not consider these two as parameters, but instead set the value 2 to number_of_wheels. This is a way to write Python-style getter and setter code.

But we can also use this method for other things, such as the "Make_noise" method. Let's see:

When we call this method, it simply returns a string "Vrrrruuuum. " "

Encapsulation: Hiding information

Encapsulation is a mechanism that restricts direct access to object data and methods. But at the same time, it makes it easier to manipulate data (the method of the object).

"Encapsulation can be used to hide data members and member functions. By this definition, encapsulation means that an internal representation of an object is generally hidden in an external view of an object definition. ”?—? Wikipedia

All internal representations of an object are hidden from the outside. Only the object itself can interact with its internal data.

First, we need to understand how open, non-public instance variables and methods work.

Public instance variables

For Python classes, we can initialize a public instance variable in our constructor method. Let's take a look at this:

In this construction method:

Here, we apply the first_name value as a parameter to the public instance variable.

In the class:

Here, we do not need to use first_name as an argument, all instance objects have a class attribute initialized with TK.

That's cool, now we've learned that we can use public instance variables and class properties. Another interesting thing about the public part is that we can manage variable values. What do I mean by that? Our object can manage its variable values: Get and Set variable values.

or in the person class, we want to set another value for its first_name variable:

That's it, we just set another value (Kaio) for the first_name instance variable and update the value. It's so simple. Because this is a public variable, we can do that.

Non-public instance variables

Here we do not use the term "private" because all properties in Python are not really private (there is no usual unnecessary effort).-PEP 8

As public instance variable (common instance variable), we can define non-public instance variable (non-public instance variable) within a constructor method or class. The grammatical difference is: for non-public instance variables (non-public instance variable), use an underscore (_) before the variable name.

"Private" instance variables that cannot be accessed from outside the object do not exist in Python. However, there is a convention that most Python code will follow: naming using underscores as prefixes (for example, _spam) should be considered a non-public part of the API (whether it is a function, method, or data member) "?-python Software Basics

Here is the sample code:

Have you seen the email variables? This is how we define non-public variables:

We can access and update it. A non-public variable is only a customary method and should be used as a non-public part of the API.

So we use a method that is internal to the class definition to implement this function. Let's implement two methods (email and update_email) to deepen our understanding:

Now we can use these two methods to update and access the nonpublic variables. Examples such as the following

1. We have initialized a new object using first_name tk and email [email protected]

2. Use the method to access the non-public variable email and output it

3. Try to set up a new email outside the class

4. We need to treat nonpublic variables as non-public parts of the API

5. Use our instance method to update nonpublic variables

6. Success! We used the helper method to update it inside the class.

Public methods

For public methods, we can also use them in classes:

Let's test it out:

Very well – we don't have any problems using it in the class.

Non-public methods

But in a non-public way, we can't do that. If we want to implement the same person class, now use the show_age non-public method with an underscore (_).

Now, we will try to invoke this non-public method with our object:

We can access and update it. A non-public approach is only a convention and should be considered a non-public part of the API.

Here is an example of how we use it:

Here is a _get_age non-public method and a show_age public method. Show_age can be used by our objects (not in our classes), and _get_age is used only within our class definitions (in the Show_age method). But again, this is usually the practice.

Package Summary

By encapsulation, we can ensure that the internal representation of an object is hidden from the outside.

Inheritance: Behavior and characteristics

Some objects have something in common: their behavior and characteristics.

For example, I inherited some of my father's characteristics and behavior. I inherited the characteristics of his eyes and hair, as well as his impatience and introverted behavior.

In object-oriented programming, a class can inherit the common characteristics (data) and behavior (methods) of another class.

Let's look at another example and implement it with Python.

Imagine a car. The number of wheels, seat capacity and maximum speed are all properties of a car. We can say that the Electriccar class inherits these same attributes from the normal Car class.

The realization of our Car class:

Once initialized, we can use all of the created instance variables. That's great.

In Python, we inherit the parent class as a child parameter. The Electriccar class can inherit our car class.

It's so simple. We do not need to implement any other method, because this class has completed the inheritance of the parent class (inherited from the Car class). Let's prove it:

It's pretty dry.

Still Silicon Valley interviewer Song Hongkang
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

From zero to Hero, a text mastering Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.