从零学习python_学习Python:从零到英雄

从零学习python

First of all, what is Python? According to its creator, Guido van Rossum, Python is a:

首先,什么是Python? 根据其创建者Guido van Rossum的说法,Python是:

“high-level programming language, and its core design philosophy is all about code readability and a syntax which allows programmers to express concepts in a few lines of code.”
“高级编程语言及其核心设计哲学全都在于代码的可读性和一种语法,该语法使程序员可以用几行代码表达概念。”

For me, the first reason to learn Python was that it is, in fact, a beautiful programming language. It was really natural to code in it and express my thoughts.

对我来说,学习Python的第一个原因是它实际上是一个漂亮的 编程语言。 编写代码并表达我的想法是很自然的。

Another reason was that we can use coding in Python in multiple ways: data science, web development, and machine learning all shine here. Quora, Pinterest and Spotify all use Python for their backend web development. So let’s learn a bit about it.

另一个原因是我们可以通过多种方式在Python中使用编码:数据科学,Web开发和机器学习在这里大放异彩。 Quora,Pinterest和Spotify都使用Python进行后端Web开发。 因此,让我们学习一下。

基础 (The Basics)

1.变量 (1. Variables)

You can think about variables as words that store a value. Simple as that.

您可以将变量视为存储值的单词。 就那么简单。

In Python, it is really easy to define a variable and set a value to it. Imagine you want to store number 1 in a variable called “one.” Let’s do it:

在Python中,定义变量并为其设置值确实很容易。 假设您要将数字1存储在名为“ one”的变量中。 我们开始做吧:

one = 1

How simple was that? You just assigned the value 1 to the variable “one.”

那有多简单? 您刚刚将值1分配给变量“ one”。

two = 2
some_number = 10000

And you can assign any other value to whatever other variables you want. As you see in the table above, the variable “two” stores the integer 2, and “some_number” stores 10,000.

您可以将任何其他分配给所需的其他变量 。 如上表所示,变量“ two ”存储整数2 ,而“ some_number ”存储10,000

Besides integers, we can also use booleans (True / False), strings, float, and so many other data types.

除了整数,我们还可以使用布尔值(真/假),字符串,浮点数和许多其他数据类型。

# booleans
true_boolean = True
false_boolean = False

# string
my_name = "Leandro Tk"

# float
book_price = 15.80
2.控制流:条件语句 (2. Control Flow: conditional statements)

If” uses an expression to evaluate whether a statement is True or False. If it is True, it executes what is inside the “if” statement. For example:

If ”使用表达式评估语句是True还是False。 如果为True,则执行“ if”语句中的内容。 例如:

if True:
  print("Hello Python If")

if 2 > 1:
  print("2 is greater than 1")

2 is greater than 1, so the “print” code is executed.

2大于1 ,因此将执行“ 打印 ”代码。

The “else” statement will be executed if the “if” expression is false.

如果“ if ”表达式为false,则将执行“ else ”语句。

if 1 > 2:
  print("1 is greater than 2")
else:
  print("1 is not greater than 2")

1 is not greater than 2, so the code inside the “else” statement will be executed.

1不大于2 ,因此将执行“ else ”语句中的代码。

You can also use an “elif” statement:

您还可以使用“ elif ”语句:

if 1 > 2:
  print("1 is greater than 2")
elif 2 > 1:
  print("1 is not greater than 2")
else:
  print("1 is equal to 2")
3.循环/迭代器 (3. Looping / Iterator)

In Python, we can iterate in different forms. I’ll talk about two: while and for.

在Python中,我们可以以不同的形式进行迭代。 我将谈论两个:

While Looping: while the statement is True, the code inside the block will be executed. So, this code will print the number from 1 to 10.

While Looping:当语句为True时,将执行块中的代码。 因此,此代码将打印从110的数字。

num = 1

while num <= 10:
    print(num)
    num += 1

The while loop needs a “loop condition.” If it stays True, it continues iterating. In this example, when num is 11 the loop condition equals False.

while循环需要一个“ 循环条件”。 如果它保持True,它将继续迭代。 在此示例中,当num11循环条件等于False

Another basic bit of code to better understand it:

另一个基本的代码可以更好地理解它:

loop_condition = True

while loop_condition:
    print("Loop Condition keeps: %s" %(loop_condition))
    loop_condition = False

The loop condition is True so it keeps iterating — until we set it to False.

循环条件True因此它会不断迭代-直到将其设置为False为止。

For Looping: you apply the variable “num” to the block, and the “for” statement will iterate it for you. This code will print the same as while code: from 1 to 10.

对于循环 :您将变量“ num ”应用于该块,“ for ”语句将为您进行迭代。 此代码将打印与while代码相同的内容:从110

for i in range(1, 11):
  print(i)

See? It is so simple. The range starts with 1 and goes until the 11th element (10 is the 10th element).

看到? 很简单。 范围从1开始,一直到第11个元素( 10是第10个元素)。

列表:收藏| 数组| 数据结构 (List: Collection | Array | Data Structure)

Imagine you want to store the integer 1 in a variable. But maybe now you want to store 2. And 3, 4, 5 …

假设您要将整数1存储在变量中。 但也许现在您想存储2和3、4、5…

Do I have another way to store all the integers that I want, but not in millions of variables? You guessed it — there is indeed another way to store them.

我是否还有另一种方式可以存储我想要的所有整数,但不能存储数百万个变量 ? 您猜对了–确实存在另一种存储方式。

List is a collection that can be used to store a list of values (like these integers that you want). So let’s use it:

List是一个集合,可用于存储值列表(例如所需的这些整数)。 因此,让我们使用它:

my_integers = [1, 2, 3, 4, 5]

It is really simple. We created an array and stored it on my_integer.

真的很简单。 我们创建了一个数组并将其存储在my_integer上

But maybe you are asking: “How can I get a value from this array?”

但是也许您在问:“如何从这个数组中获取价值?”

Great question. List has a concept called index. The first element gets the index 0 (zero). The second gets 1, and so on. You get the idea.

好问题。 List有一个称为index的概念。 第一个元素的索引为0(零)。 第二个为1,依此类推。 你明白了。

To make it clearer, we can represent the array and each element with its index. I can draw it:

为了更加清楚,我们可以用其索引表示数组和每个元素。 我可以画出来:

Using the Python syntax, it’s also simple to understand:

使用Python语法,也很容易理解:

my_integers = [5, 7, 1, 3, 4]
print(my_integers[0]) # 5
print(my_integers[1]) # 7
print(my_integers[4]) # 4

Imagine that you don’t want to store integers. You just want to store strings, like a list of your relatives’ names. Mine would look something like this:

想象一下,您不想存储整数。 您只想存储字符串,例如您的亲戚名字列表。 我的看起来像这样:

relatives_names = [
  "Toshiaki",
  "Juliana",
  "Yuji",
  "Bruno",
  "Kaio"
]

print(relatives_names[4]) # Kaio

It works the same way as integers. Nice.

它的工作方式与整数相同。 真好

We just learned how Lists indices work. But I still need to show you how we can add an element to the List data structure (an item to a list).

我们刚刚了解了Lists索引的工作方式。 但是我仍然需要向您展示如何将元素添加到List数据结构( List的项)。

The most common method to add a new value to a List is append. Let’s see how it works:

List添加新值的最常见方法是append 。 让我们看看它是如何工作的:

bookshelf = []
bookshelf.append("The Effective Engineer")
bookshelf.append("The 4 Hour Work Week")
print(bookshelf[0]) # The Effective Engineer
print(bookshelf[1]) # The 4 Hour Work Week

append is super simple. You just need to apply the element (eg. “The Effective Engineer”) as the append parameter.

append非常简单。 您只需要应用元素(例如“ 有效工程师 ”)作为append参数。

Well, enough about Lists. Let’s talk about another data structure.

好吧,关于Lists足够了 让我们谈谈另一种数据结构。

词典:键值数据结构 (Dictionary: Key-Value Data Structure)

Now we know that Lists are indexed with integer numbers. But what if we don’t want to use integer numbers as indices? Some data structures that we can use are numeric, string, or other types of indices.

现在我们知道Lists是用整数索引的。 但是,如果我们不想使用整数作为索引怎么办? 我们可以使用的某些数据结构是数字,字符串或其他类型的索引。

Let’s learn about the Dictionary data structure. Dictionary is a collection of key-value pairs. Here’s what it looks like:

让我们了解Dictionary数据结构。 Dictionary是键值对的集合。 看起来是这样的:

dictionary_example = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

The key is the index pointing to the value. How do we access the Dictionary value? You guessed it — using the key. Let’s try it:

关键是指向 价值 。 我们如何访问Dictionary ? 您猜对了-使用 。 让我们尝试一下:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian"
}

print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro
print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk
print("And by the way I'm %s" %(dictionary_tk["nationality"])) # And by the way I'm Brazilian

I created a Dictionary about me. My name, nickname, and nationality. Those attributes are the Dictionary keys.

我创建了一个关于我的Dictionary 。 我的名字,昵称和国籍。 这些属性是Dictionary

As we learned how to access the List using index, we also use indices (keys in the Dictionary context) to access the value stored in the Dictionary.

当我们学习了如何使用索引访问List ,我们还使用了索引( Dictionary上下文中的 )来访问存储在Dictionary

In the example, I printed a phrase about me using all the values stored in the Dictionary. Pretty simple, right?

在示例中,我使用存储在Dictionary中的所有值打印了一个关于我的短语。 很简单,对吧?

Another cool thing about Dictionary is that we can use anything as the value. In the Dictionary I created, I want to add the key “age” and my real integer age in it:

关于Dictionary另一个很酷的事情是,我们可以使用任何东西作为值。 在Dictionary 我创建了,我想在其中添加 “ age”和我的真实整数年龄:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian",
  "age": 24
}

print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro
print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk
print("And by the way I'm %i and %s" %(dictionary_tk["age"], dictionary_tk["nationality"])) # And by the way I'm Brazilian

Here we have a key (age) value (24) pair using string as the key and integer as the value.

在这里,我们有一个密钥 (年龄) (24)对,使用string作为密钥,而integer作为

As we did with Lists, let’s learn how to add elements to a Dictionary. The key pointing to a value is a big part of what Dictionary is. This is also true when we are talking about adding elements to it:

正如我们对Lists所做的那样,让我们​​学习如何向Dictionary添加元素。 关键 指向一个 价值Dictionary的重要组成部分。 当我们谈论向其添加元素时,也是如此:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian"
}

dictionary_tk['age'] = 24

print(dictionary_tk) # {'nationality': 'Brazilian', 'age': 24, 'nickname': 'Tk', 'name': 'Leandro'}

We just need to assign a value to a Dictionary key. Nothing complicated here, right?

我们只需要给Dictionary分配一个 。 这里没什么复杂的,对吧?

迭代:遍历数据结构 (Iteration: Looping Through Data Structures)

As we learned in the Python Basics, the List iteration is very simple. We Python developers commonly use For looping. Let’s do it:

正如我们在Python基础知识中所了解的那样, List迭代非常简单。 我们Python 开发人员通常使用For循环。 我们开始做吧:

bookshelf = [
  "The Effective Engineer",
  "The 4-hour Workweek",
  "Zero to One",
  "Lean Startup",
  "Hooked"
]

for book in bookshelf:
    print(book)

So for each book in the bookshelf, we (can do everything with it) print it. Pretty simple and intuitive. That’s Python.

因此,对于书架中的每本书,我们( 可以使用它来做所有事情 )打印它。 非常简单直观。 那是Python。

For a hash data structure, we can also use the for loop, but we apply the key :

对于散列数据结构,我们也可以使用for循环,但是我们应用key

dictionary = { "some_key": "some_value" }

for key in dictionary:
    print("%s --> %s" %(key, dictionary[key]))
    
# some_key --> some_value

This is an example how to use it. For each key in the dictionary , we print the key and its corresponding value.

这是一个如何使用它的示例。 对于dictionary中的每个key ,我们将print key及其对应的value

Another way to do it is to use the iteritems method.

另一种方法是使用iteritems方法。

dictionary = { "some_key": "some_value" }

for key, value in dictionary.items():
    print("%s --> %s" %(key, value))

# some_key --> some_value

We did name the two parameters as key and value, but it is not necessary. We can name them anything. Let’s see it:

我们确实将两个参数命名为keyvalue ,但这不是必需的。 我们可以给他们起任何名字。 让我们来看看它:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian",
  "age": 24
}

for attribute, value in dictionary_tk.items():
    print("My %s is %s" %(attribute, value))
    
# My name is Leandro
# My nickname is Tk
# My nationality is Brazilian
# My age is 24

We can see we used attribute as a parameter for the Dictionary key, and it works properly. Great!

我们可以看到我们使用attribute作为Dictionary key的参数,并且可以正常工作。 大!

类和对象 (Classes & Objects)

一点理论: (A little bit of theory:)

Objects are a representation of real world objects like cars, dogs, or bikes. The objects share two main characteristics: data and behavior.

对象代表现实世界中的对象,例如汽车,狗或自行车。 对象具有两个主要特征: 数据行为

Cars have data, like number of wheels, number of doors, and seating capacity They also exhibit behavior: they can accelerate, stop, show how much fuel is left, and so many other things.

汽车具有数据,例如车轮数量,门数量和座位容量。它们还表现出一些行为 :它们可以加速,停止,显示还剩多少燃料以及许多其他事情。

We identify data as attributes and behavior as methods in object-oriented programming. Again:

我们确定的数据 属性行为在面向对象的程序设计方法 。 再次:

Data → Attributes and Behavior → Methods

数据→属性和行为→方法

And a Class is the blueprint from which individual objects are created. In the real world, we often find many objects with the same type. Like cars. All the same make and model (and all have an engine, wheels, doors, and so on). Each car was built from the same set of blueprints and has the same components.

是从中创建单个对象的蓝图。 在现实世界中,我们经常发现许多具有相同类型的对象。 像汽车。 相同的品牌和型号(都具有发动机,车轮,门等)。 每辆汽车都是根据相同的蓝图建造的,具有相同的组件。

Python面向对象的编程模式:ON (Python Object-Oriented Programming mode: ON)

Python, as an Object-Oriented programming language, has these concepts: class and object.

作为一种面向对象的编程语言,Python具有以下概念: classobject

A class is a blueprint, a model for its objects.

类是一个蓝图,是其对象的模型。

So again, a class it is just a model, or a way to define attributes and behavior (as we talked about in the theory section). As an example, a vehicle class has its own attributes that define what objects are vehicles. The number of wheels, type of tank, seating capacity, and maximum velocity are all attributes of a vehicle.

同样,一个类只是一个模型,或者是定义属性行为的一种方式(正如我们在理论部分所讨论的)。 例如,车辆具有其自己的属性 ,这些属性定义什么对象是车辆。 车轮数量,油箱类型,座位容量和最大速度都是车辆的属性。

With this in mind, let’s look at Python syntax for classes:

考虑到这一点,让我们看一下类的 Python语法:

class Vehicle:
    pass

We define classes with a class statement — and that’s it. Easy, isn’t it?

我们使用类声明定义类,仅此而已。 很简单,不是吗?

Objects are instances of a class. We create an instance by naming the class.

对象类的实例。 我们通过命名类来创建实例。

car = Vehicle()
print(car) # <__main__.Vehicle instance at 0x7fb1de6c2638>

Here car is an object (or instance) of the class Vehicle.

这里carVehicle 对象 (或实例)。

Remember that our vehicle class has four attributes: number of wheels, type of tank, seating capacity, and maximum velocity. We set all these attributes when creating a vehicle object. So here, we define our class to receive data when it initiates it:

请记住,我们的车辆类别具有四个属性 :车轮数量,油箱类型,可容纳人数和最大速度。 我们在创建车辆对象时设置所有这些属性 。 因此,在这里,我们定义我们的以在其启动时接收数据:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

We use the init method. We call it a constructor method. So when we create the vehicle object, we can define these attributes. Imagine that we love the Tesla Model S, and we want to create this kind of object. It has four wheels, runs on electric energy, has space for five seats, and the maximum velocity is 250km/hour (155 mph). Let’s create this object:

我们使用init 方法 。 我们称其为构造函数方法。 因此,当我们创建车辆对象时 ,我们可以定义这些属性 。 想象一下,我们喜欢特斯拉Model S,并且想要创建这种对象 。 它有四个轮子,依靠电能运行,可以容纳五个座位,最大速度为250公里/小时(155英里/小时)。 让我们创建这个对象:

tesla_model_s = Vehicle(4, 'electric', 5, 250)

Four wheels + electric “tank type” + five seats + 250km/hour maximum speed.

四轮+电动“油箱式” +五座+最高时速250公里/小时。

All attributes are set. But how can we access these attributes’ values? We send a message to the object asking about them. We call it a method. It’s the object’s behavior. Let’s implement it:

设置所有属性。 但是我们如何访问这些属性的值? 我们向对象发送一条消息,询问有关它们的信息 。 我们称其为方法 。 这是对象的行为 。 让我们实现它:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

    def number_of_wheels(self):
        return self.number_of_wheels

    def set_number_of_wheels(self, number):
        self.number_of_wheels = number

This is an implementation of two methods: number_of_wheels and set_number_of_wheels. We call it getter & setter. Because the first gets the attribute value, and the second sets a new value for the attribute.

这是两个方法的实现: number_of_wheelsset_number_of_wheels 。 我们称之为gettersetter 。 因为第一个获取属性值,第二个为属性设置新值。

In Python, we can do that using @property (decorators) to define getters and setters. Let’s see it with code:

在Python中,我们可以使用@property ( decorators )定义getterssetters来做到这一点。 我们来看一下代码:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity
    
    @property
    def number_of_wheels(self):
        return self.__number_of_wheels
    
    @number_of_wheels.setter
    def number_of_wheels(self, number):
        self.__number_of_wheels = number

And we can use these methods as attributes:

我们可以将这些方法用作属性:

tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2
print(tesla_model_s.number_of_wheels) # 2

This is slightly different than defining methods. The methods work as attributes. For example, when we set the new number of wheels, we don’t apply two as a parameter, but set the value 2 to number_of_wheels. This is one way to write pythonic getter and setter code.

这与定义方法略有不同。 这些方法用作属性。 例如,当我们设置新的车轮数时,我们不应用两个作为参数,而是将数值2设置为number_of_wheels 。 这是编写pythonic gettersetter代码的一种方法。

But we can also use methods for other things, like the “make_noise” method. Let’s see it:

但是我们也可以将方法用于其他用途,例如“ make_noise ”方法。 让我们来看看它:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

    def make_noise(self):
        print('VRUUUUUUUM')

When we call this method, it just returns a string VRRRRUUUUM.

当我们调用此方法时,它仅返回字符串 VRRRRUUUUM。

tesla_model_s = Vehicle(4, 'electric', 5, 250)
tesla_model_s.make_noise() # VRUUUUUUUM

封装:隐藏信息 (Encapsulation: Hiding Information)

Encapsulation is a mechanism that restricts direct access to objects’ data and methods. But at the same time, it facilitates operation on that data (objects’ methods).

封装是一种限制直接访问对象的数据和方法的机制。 但是,与此同时,它便于对该数据(对象的方法)进行操作。

“Encapsulation can be used to hide data members and members function. Under this definition, encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s definition.” — Wikipedia

封装可以用来隐藏数据成员和成员函数。 在这种定义下,封装意味着对象的内部表示通常在对象定义之外的视图中是隐藏的。” —维基百科

All internal representation of an object is hidden from the outside. Only the object can interact with its internal data.

对象的所有内部表示都从外部隐藏。 只有对象可以与其内部数据进行交互。

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

首先,我们需要了解publicnon-public实例变量和方法的工作方式。

公共实例变量 (Public Instance Variables)

For a Python class, we can initialize a public instance variable within our constructor method. Let’s see this:

对于Python类,我们可以在构造函数方法中初始化一个public instance variable 。 让我们看看这个:

Within the constructor method:

在构造方法中:

class Person:
    def __init__(self, first_name):
        self.first_name = first_name

Here we apply the first_name value as an argument to the public instance variable.

在这里,我们将first_name值作为参数应用到public instance variable

tk = Person('TK')
print(tk.first_name) # => TK

Within the class:

在班级内:

class Person:
    first_name = 'TK'

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

在这里,我们不需要将first_name用作参数,并且所有实例对象都将具有使用TK初始化的class attribute

tk = Person()
print(tk.first_name) # => TK

Cool. We have now learned that we can use public instance variables and class attributes. Another interesting thing about the public part is that we can manage the variable value. What do I mean by that? Our object can manage its variable value: Get and Set variable values.

凉。 现在我们知道可以使用public instance variablesclass attributes 。 关于public部分的另一个有趣的事情是,我们可以管理变量值。 那是什么意思 我们的object可以管理其变量值: GetSet变量值。

Keeping the Person class in mind, we want to set another value to its first_name variable:

牢记Person类,我们想为其first_name变量设置另一个值:

tk = Person('TK')
tk.first_name = 'Kaio'
print(tk.first_name) # => Kaio

There we go. We just set another value (kaio) to the first_name instance variable and it updated the value. Simple as that. Since it’s a public variable, we can do that.

好了 我们仅将另一个值( kaio )设置为first_name实例变量,它会更新该值。 就那么简单。 由于这是一个public变量,我们可以做到这一点。

非公共实例变量 (Non-public Instance Variable)

We don’t use the term “private” here, since no attribute is really private in Python (without a generally unnecessary amount of work). — PEP 8

我们在这里不使用术语“私有”,因为在Python中没有任何属性是真正私有的(通常没有不必要的工作量)。 — PEP 8

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

作为public instance variable ,我们可以在构造函数方法中或在类中定义non-public instance variable 。 语法差异是:对于non-public instance variables ,请在variable名称前使用下划线( _ )。

“‘Private’ instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member)” — Python Software Foundation

在Python中不存在只能从对象内部访问的“私有”实例变量。 但是,大多数Python代码遵循一个约定:以下划线开头的名称(例如_spam )应被视为API的非公开部分(无论是函数,方法还是数据成员) ” — Python软件基金会

Here’s an example:

这是一个例子:

class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name
        self._email = email

Did you see the email variable? This is how we define a non-public variable :

您看到email变量了吗? 这就是我们定义non-public variable

tk = Person('TK', 'tk@mail.com')
print(tk._email) # tk@mail.com

We can access and update it. Non-public variables are just a convention and should be treated as a non-public part of the API.

我们可以访问和更新它。 Non-public variables只是一个约定,应将其视为API的非公共部分。

So we use a method that allows us to do it inside our class definition. Let’s implement two methods (email and update_email) to understand it:

因此,我们使用一种允许在类定义中进行操作的方法。 让我们实现两种方法( emailupdate_email )来理解它:

class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name
        self._email = email

    def update_email(self, new_email):
        self._email = new_email

    def email(self):
        return self._email

Now we can update and access non-public variables using those methods. Let’s see:

现在,我们可以使用这些方法更新和访问non-public variables 。 让我们来看看:

tk = Person('TK', 'tk@mail.com')
print(tk.email()) # => tk@mail.com
# tk._email = 'new_tk@mail.com' -- treat as a non-public part of the class API
print(tk.email()) # => tk@mail.com
tk.update_email('new_tk@mail.com')
print(tk.email()) # => new_tk@mail.com
  1. We initiated a new object with first_name TK and email tk@mail.com

    我们使用first_name TK和email tk@mail.com发起了一个新对象

  2. Printed the email by accessing the non-public variable with a method

    通过使用方法访问non-public variable来打印电子邮件

  3. Tried to set a new email out of our class

    试图在我们班级以外设置一个新email

  4. We need to treat non-public variable as non-public part of the API

    我们需要将non-public variable视为API的non-public部分

  5. Updated the non-public variable with our instance method

    使用我们的实例方法更新了non-public variable

  6. Success! We can update it inside our class with the helper method

    成功! 我们可以使用helper方法在类中更新它
公开方法 (Public Method)

With public methods, we can also use them out of our class:

使用public methods ,我们也可以在类之外使用它们:

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age

    def show_age(self):
        return self._age

Let’s test it:

让我们测试一下:

tk = Person('TK', 25)
print(tk.show_age()) # => 25

Great — we can use it without any problem.

太好了-我们可以毫无问题地使用它。

非公开方法 (Non-public Method)

But with non-public methods we aren’t able to do it. Let’s implement the same Person class, but now with a show_age non-public method using an underscore (_).

但是使用non-public methods我们无法做到这一点。 让我们实现相同的Person类,但是现在使用带下划线( _ )的show_age non-public method

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age

    def _show_age(self):
        return self._age

And now, we’ll try to call this non-public method with our object:

现在,我们将尝试用我们的对象调用此non-public method

tk = Person('TK', 25)
print(tk._show_age()) # => 25

We can access and update it. Non-public methods are just a convention and should be treated as a non-public part of the API.

我们可以访问和更新它。 Non-public methods只是一个约定,应被视为API的非公共部分。

Here’s an example for how we can use it:

这是我们如何使用它的示例:

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age

    def show_age(self):
        return self._get_age()

    def _get_age(self):
        return self._age

tk = Person('TK', 25)
print(tk.show_age()) # => 25

Here we have a _get_age non-public method and a show_age public method. The show_age can be used by our object (out of our class) and the _get_age only used inside our class definition (inside show_age method). But again: as a matter of convention.

这里我们有一个_get_age non-public method和一个show_age public methodshow_age可以由我们的对象使用(在我们的类之外), _get_age只能在我们的类定义内部使用(在show_age方法内部)。 但同样:作为惯例。

封装总结 (Encapsulation Summary)

With encapsulation we can ensure that the internal representation of the object is hidden from the outside.

通过封装,我们可以确保从外部隐藏对象的内部表示。

继承:行为和特征 (Inheritance: behaviors and characteristics)

Certain objects have some things in common: their behavior and characteristics.

某些对象有一些共同点:它们的行为和特征。

For example, I inherited some characteristics and behaviors from my father. I inherited his eyes and hair as characteristics, and his impatience and introversion as behaviors.

例如,我从父亲那里继承了一些特征和行为。 我继承了他的眼睛和头发作为特征,继承了他的不耐烦和内向作为行为。

In object-oriented programming, classes can inherit common characteristics (data) and behavior (methods) from another class.

在面向对象的编程中,类可以从另一个类继承通用特征(数据)和行为(方法)。

Let’s see another example and implement it in Python.

让我们来看另一个示例,并在Python中实现它。

Imagine a car. Number of wheels, seating capacity and maximum velocity are all attributes of a car. We can say that an ElectricCar class inherits these same attributes from the regular Car class.

想像一辆汽车。 车轮数量,座位容量和最大速度都是汽车的属性。 我们可以说 ElectricCar类从常规Car类继承这些相同的属性。

class Car:
    def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

Our Car class implemented:

我们的Car课程已实施:

my_car = Car(4, 5, 250)
print(my_car.number_of_wheels)
print(my_car.seating_capacity)
print(my_car.maximum_velocity)

Once initiated, we can use all instance variables created. Nice.

一旦启动,我们就可以使用所有创建的instance variables 。 真好

In Python, we apply a parent class to the child class as a parameter. An ElectricCar class can inherit from our Car class.

在Python中,我们将parent class child class作为参数应用于child classElectricCar类可以从我们的Car类继承。

class ElectricCar(Car):
    def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
        Car.__init__(self, number_of_wheels, seating_capacity, maximum_velocity)

Simple as that. We don’t need to implement any other method, because this class already has it (inherited from Car class). Let’s prove it:

就那么简单。 我们不需要实现任何其他方法,因为该类已经拥有它(从Car类继承)。 让我们证明一下:

my_electric_car = ElectricCar(4, 5, 250)
print(my_electric_car.number_of_wheels) # => 4
print(my_electric_car.seating_capacity) # => 5
print(my_electric_car.maximum_velocity) # => 250

Beautiful.

美丽。

而已! (That’s it!)

We learned a lot of things about Python basics:

我们了解了有关Python基础知识的很多知识:

  • How Python variables work

    Python变量如何工作
  • How Python conditional statements work

    Python条件语句如何工作
  • How Python looping (while & for) works

    Python循环(while和for)如何工作
  • How to use Lists: Collection | Array

    如何使用清单:收藏夹| 数组
  • Dictionary Key-Value Collection

    字典键值集合
  • How we can iterate through these data structures

    我们如何遍历这些数据结构
  • Objects and Classes

    对象和类
  • Attributes as objects’ data

    属性作为对象的数据
  • Methods as objects’ behavior

    方法作为对象的行为
  • Using Python getters and setters & property decorator

    使用Python getter和setter和属性装饰器
  • Encapsulation: hiding information

    封装:隐藏信息
  • Inheritance: behaviors and characteristics

    继承:行为和特征

Congrats! You completed this dense piece of content about Python.

恭喜! 您已经完成了有关Python的内容丰富的内容。

If you want a complete Python course, learn more real-world coding skills and build projects, try One Month Python Bootcamp. See you there ☺

如果您想学习一门完整的Python课程,请学习更多实际的编码技巧并构建项目,请尝试一个月Python Bootcamp 。 在那里见you

For more stories and posts about my journey learning & mastering programming, follow my publication The Renaissance Developer.

有关我的旅程学习和掌握编程的更多故事和帖子,请关注我的出版物The Renaissance Developer

Have fun, keep learning, and always keep coding.

玩得开心,继续学习,并始终保持编码。

My Twitter & Github. ☺

我的TwitterGithub 。 ☺

翻译自: https://www.freecodecamp.org/news/learning-python-from-zero-to-hero-120ea540b567/

从零学习python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值