Python -- From Zero to Hero

这里写图片描述
翻译自:https://medium.freecodecamp.org/learning-python-from-zero-to-hero-120ea540b567

此篇博客,简单易懂的描述了python的基础知识,适用于0基础入门的同学,1小时基本就能搞懂。所以翻译了后,分享…


首先,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.”

高层次的编程语言,其核心设计理念是关于代码可读性和语法,它允许程序员用几行代码表达概念

对我而言,学习Python的第一个原因是它实际上是一个漂亮的编程语言。编写代码并表达我的想法是非常自然的。 另一个原因是我们可以用多种方式在Python中使用编码:数据科学,Web开发和机器学习都在这里闪耀。
Quora,Pinterest和Spotify都使用Python进行后端Web开发。所以让我们来了解一下。

基础

1.变量

您可以将变量看作是存储值的单词。就那么简单。
在Python中,定义一个变量并为其设置一个值是很容易的。想象一下,你想把数字1存储在一个名为“one”的变量中。让我们来做:

one = 1

非常简单?您只是将值1分配给变量“one”

two = 2
some_number = 10000

你可以给任何其他的变量赋值。如上表所示,变量“two”存储整数2,“some_number”存储10,000。

除了整数之外,我们还可以使用布尔值(真/假),字符串,浮点数等多种数据类型。

# booleans
true_boolean = True
false_boolean = False

# string
my_name = "Leandro Tk"

# float
book_price = 15.80

2.控制流程:有条件的陈述

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

if True:
  print("Hello Python If")

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

2大于1,所以执行“打印”代码。
如果“if”表达式为false,则会执行“else”语句。

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

1不大于2,所以“else”语句中的代码将被执行。
您也可以使用“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.循环/迭代器

在Python中,我们可以以不同的形式进行迭代。我会谈论两个:while和for。
While循环:当语句为True时,块内的代码将被执行。所以,这个代码将打印从1到10的数字

num = 1

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

while循环需要一个“循环条件”。如果它保持为真,它将继续迭代。在这个例子中,当num是11时,循环条件等于False

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

loop_condition = True

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

环条件是True,所以它保持迭代 - 直到我们将其设置为False。

对于循环:将变量“num”应用于块,“for”语句将为您迭代。此代码将打印与代码相同的:从1到10。

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

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

List: Collection | Array | Data Structure

想象一下,你想把整数1存储在一个变量中。但也许现在你想要存储2.和3,4,5 …
我有另一种方法来存储我想要的所有整数,但不是以百万计的变量吗?你猜对了 - 确实有另一种方法来存储它们。
List是一个可以用来存储值列表的集合(就像你想要的这些整数一样)。那么让我们使用它:

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

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

但是也许你在问:“我怎样才能从这个阵列中获得价值?
伟大的问题。列表有一个叫做索引的概念。第一个元素获取索引0(零)。第二个取1,依此类推。你明白了。
为了使其更清楚,我们可以用它的索引来表示数组和每个元素。我可以画出来:
这里写图片描述

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

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

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

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

print(relatives_names[4]) # Kaio

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

我们刚刚学习了列表索引如何工作。但是我仍然需要向您展示如何将元素添加到List数据结构(一个项目到列表)。

将一个新值添加到List的最常见方法是追加。让我们看看它是如何工作的:

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

追加是非常简单的。您只需要将元素(例如“The Effective Engineer”)作为附加参数.

那么,关于列表就够了。我们来谈谈另一个数据结构。

Dictionary: Key-Value Data Structure

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

让我们来了解一下Dictionary的数据结构。字典是键值对的集合。以下是它的样子:

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

关键是指向这个值的索引。我们如何访问字典值?你猜对了 - 用钥匙。让我们试试看:

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

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

当我们学习如何使用索引访问列表时,我们也使用索引(Dictionary上下文中的键)来访问Dictionary中存储的值。

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

于词典的另一个很酷的事情是,我们可以使用任何东西作为价值。在我创建的词典中,我想添加键“年龄”和我的实际整数年龄:

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

在这里,我们有一个键(年龄)值(24)对使用字符串作为键和整数作为值。

正如我们对列表所做的那样,让我们学习如何将元素添加到字典中。指向一个值的键是Dictionary的一个重要组成部分。当我们正在讨论添加元素时,也是如此:

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

dictionary_tk['age'] = 24

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

我们只需要为一个Dictionary键分配一个值。没有什么复杂的,对吧?

Iteration: Looping Through Data Structures

正如我们在Python基础知识中学到的,List迭代非常简单。我们Python开发者通常使用For循环。我们开始做吧:

bookshelf = [
  "The Effective Engineer",
  "The 4 hours work week",
  "Zero to One",
  "Lean Startup",
  "Hooked"
]

for book in bookshelf:
    print(book)

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

对于一个散列数据结构,我们也可以使用for循环,但是我们使用这个键:

dictionary = { "some_key": "some_value" }

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

# some_key --> some_value

这是一个如何使用它的例子。对于字典中的每个键,我们都会打印键和相应的值

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

dictionary = { "some_key": "some_value" }

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

# some_key --> some_value

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

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
view rawdictionary_iteration_2.py hosted withby GitHub

我们可以看到我们使用属性作为Dictionary键的参数,并且它正常工作。Great!

Classes & Objects

一点理论:

对象是像汽车,狗或自行车的真实世界物体的表示。这些对象共享两个主要特征:数据和行为。

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

我们将数据识别为属性和行为,作为面向对象编程中的方法。再次:

数据→属性和行为→方法

一个类是创建单个对象的蓝图。在现实世界中,我们经常发现许多相同类型的对象。像汽车。所有相同的品牌和型号(都有一个引擎,轮子,门等等)。
每辆车都是由同一套蓝图构成的,并具有相同的组件。

Python面向对象的编程模式:ON

作为一种面向对象的编程语言,Python有这样的概念:类和对象。

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

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

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

class Vehicle:
    pass

我们用类声明来定义类 - 就是这样。很简单,不是吗?

对象是一个类的实例。我们通过命名类创建一个实例。

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

这里汽车是汽车类的一个对象(或实例)。

请记住,我们的车辆类别有四个属性:车轮数量,坦克类型,座位容量和最大速度。创建车辆对象时,我们设置了所有这些属性。所以在这里,我们定义我们的类来接收数据,当它启动它:

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

我们使用init方法。我们称之为构造函数方法。所以当我们创建车辆对象时,我们可以定义这些属性。想象一下,我们喜欢特斯拉模型S,我们想创建这种类型的对象。有四个轮子,以电能运行,有五个座位的空间,最高时速为250公里/小时(155英里/小时)。我们来创建这个对象:

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

四轮+电动“坦克型”+五座+最高时速250km /小时。

所有的属性都被设置。但是我们如何才能访问这些属性的值呢?我们发送消息给对象,询问他们。我们称之为一种方法。这是对象的行为。让我们来实现它:

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

是两个方法的实现:number_of_wheels和set_number_of_wheels。我们称之为getter&setter。因为第一个获取属性值,第二个为属性设置一个新的值。

在Python中,我们可以使用@property(装饰器)来定义getter和setter。让我们看看代码:

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

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

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

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

但是我们也可以使用其他方法,比如“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')

当我们调用这个方法时,它只是返回一个字符串“VRRRUUUUM”。

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

封装:隐藏信息

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

“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

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

首先,我们需要了解公共和非公共实例变量和方法是如何工作的。

Public Instance Variables

于Python类,我们可以在我们的构造函数方法中初始化一个公共实例变量。我们来看看

在构造方法中:

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

在这里,我们将first_name值作为参数应用于公共实例变量。

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

Within the class:

class Person:
    first_name = 'TK'

在这里,我们不需要将first_name作为参数,所有的实例对象都有一个用TK初始化的类属性。

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

Cool 现在我们已经了解到,我们可以使用公共实例变量和类属性。关于公共部分的另一个有趣的事情是我们可以管理变量值。这是什么意思?我们的对象可以管理它的变量值:Get和Set变量值。

记住Person类,我们想为它的first_name变量设置另一个值:

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

我们走了我们只是为first_name实例变量设置另一个值(kaio),并更新了值。就那么简单。由于这是一个公共变量,我们可以做到这一点。

非公开实例变量

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

作为公共实例变量,我们可以在构造函数方法内或类内定义非公共实例变量。语法不同之处在于:对于非公共实例变量,请在变量名称前使用下划线(_)。

“‘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

Here’s an example:

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

你看到电子邮件变量了吗?这是我们如何定义一个非公共变量:

tk = Person('TK', '[email protected]')
print(tk._email) # tk@mail.com

我们可以访问和更新它。非公共变量只是一个惯例,应该被视为API的非公开部分。

所以我们使用一个方法,允许我们在我们的类定义里面做。我们来实现两个方法(email和update_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

现在我们可以使用这些方法更新和访问非公共变量。让我们来看看

tk = Person('TK', '[email protected]')
print(tk.email()) # => tk@mail.com
tk._email = '[email protected]'
print(tk.email()) # => tk@mail.com
tk.update_email('[email protected]')
print(tk.email()) # => new_tk@mail.com
  • 我们用first_name TK和email [email protected]发起了一个新的对象
  • 通过使用方法访问非公共变量来打印电子邮件
  • 试图设置一个新的电子邮件
  • 我们需要将非公共变量视为API的非公开部分
  • 用我们的实例方法更新了非公共变量
  • 成功!我们可以使用helper方法在我们的类中更新它

Public Method

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

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

很好 - 我们可以使用它没有任何问题。

非公开的方法

但是用非公开的方法,我们无法做到这一点。让我们实现相同的Person类,但是现在使用一个使用下划线(_)的show_age非公共方法。

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

    def _show_age(self):
        return self._age

现在,我们将尝试用我们的对象来调用这个非公开的方法:

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

这里有一个_get_age非公开方法和一个show_age公共方法。 show_age可以被我们的对象(不在我们的类中)使用,而_get_age只用在我们的类定义里面(在show_age方法里面)。但是,作为惯例,也是如此。

封装摘要

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

继承:行为和特征

某些物体有一些共同之处:它们的行为和特征。

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

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

我们来看另一个例子,并用Python实现它。

想象一下汽车。车轮数量,座位容量和最大速度都是一辆车的属性。我们可以说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:

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

在Python中,我们将父类应用于子类作为参数。 ElectricCar类可以继承我们的Car类。

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

就那么简单。我们不需要实现任何其他方法,因为这个类已经有了它(继承自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

我们学到了很多关于Python基础的知识:

  • Python变量如何工作
  • Python条件语句如何工作
  • Python循环(while和for)是如何工作的
  • 如何使用列表:Collection |排列
  • 字典键值集合
  • 我们如何遍历这些数据结构
  • 对象和类
  • 属性作为对象的数据
  • 方法作为对象的行为
  • 使用Python获取器和设置器和属性装饰器
  • 封装:隐藏信息
  • 继承:行为和特征

恭喜!您完成了关于Python的这个密集的内容。

Have fun, keep learning, and always keep coding.

猜你喜欢

转载自blog.csdn.net/u010926176/article/details/79270291