https://ai./page/TextTranslation/830 2018-10-15 15:24:33 發(fā)起:余杭 校對:醬番梨 審核:醬番梨 參與翻譯(1人): 英文原文:Learning Python: From Zero to Hero 標簽: Python 標題 Learning Python: From Zero to Hero 新手必看:手把手教你入門 Python by 啦啦啦2 01 First of all, what is Python? According to its creator, Guido van Rossum, Python is a: “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 beautifulprogramming language. It was really natural to code in it and express my thoughts. 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是什么?據(jù)它的創(chuàng)始人Guido van Rossum而言, “Python是一種高級編程語言,它的核心設計思想是代碼可讀性和允許程序員用幾行代碼來表達觀點的語法?!?/p> 就我而言,學習Python的首要理由是,它事實上是一種優(yōu)雅的編程語言,我可以很自然地進行編程和表達想法。 另一個原因就是在許多方面都可以用它來編程:數(shù)據(jù)科學、web開發(fā)以及機器學習都會通過它而大放光彩。Quora, Pinterest and Spotify都用它來做后臺web開發(fā)。那么讓我們一起來了解一下吧! by CONFIDANT 02 The Basics1. VariablesYou 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: How simple was that? You just assigned the value 1 to the variable “one.” 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. Besides integers, we can also use booleans (True / False), strings, float, and so many other data types. 2. Control Flow: conditional statements基礎 你可以把變量當成存儲值的字符,就是這么簡單。 one = 1 這到底有多簡單呢?你只需要把值1賦給變量“one”。 two = 2some_number = 10000 而且你可以將其它任何值賦給其它任何變量。正如上表中你看到的那樣,變量“two”存儲整數(shù)2,“some_number”存儲10000。 2.控制流:條件語句 by CONFIDANT 03 “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: 2 is greater than 1, so the “print” code is executed. The “else” statement will be executed if the “if” expression is false. 1 is not greater than 2, so the code inside the “else” statement will be executed. You can also use an “elif” statement: 3. Looping / IteratorIn Python, we can iterate in different forms. I’ll talk about two: while and for. 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. The while loop needs a “l(fā)oop condition.” If it stays True, it continues iterating. In this example, when Another basic bit of code to better understand it: The loop condition is 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. See? It is so simple. The range starts with “If”是一種判斷語句真假的表達。若為真,就執(zhí)行“if”內(nèi)部語句。比如: if True: print("Hello Python If")if 2 > 1: print("2 is greater than 1") 2比1大,因此就執(zhí)行“print”代碼。 如果“if”語句為假就會執(zhí)行“else”語句。 if 1 > 2: print("1 is greater than 2")else: print("1 is not greater than 2") 1不大于2,因此就會執(zhí)行“else”內(nèi)部語句。 你也可以使用“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.循環(huán)/迭代 num = 1while num <= 10: print(num) num += 1 while循環(huán)需要“循環(huán)條件”,若它為真就會執(zhí)行循環(huán)。在本例中,當 另一種基本代碼更容易理解: loop_condition = Truewhile loop_condition: print("Loop Condition keeps: %s" %(loop_condition)) loop_condition = False 循環(huán)條件為真就執(zhí)行循環(huán)直到循環(huán)條件置為假為止。 for i in range(1, 11): print(i) 理解?很簡單。從1開始進行直到11,10是第十個元素。 by CONFIDANT 04 List: Collection | Array | Data StructureImagine you want to store the integer 1 in a variable. But maybe now you want to store 2. And 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.
It is really simple. We created an array and stored it on my_integer. But maybe you are asking: “How can I get a value from this array?” Great question. 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: 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: It works the same way as integers. Nice. We just learned how The most common method to add a new value to a
Well, enough about 列表:包|數(shù)組|數(shù)據(jù)結構 my_integers = [1, 2, 3, 4, 5] 真的很簡單。我們構造一個數(shù)組,并將它存在my_integer。
my_integers = [5, 7, 1, 3, 4]print(my_integers[0]) # 5print(my_integers[1]) # 7print(my_integers[4]) # 4 假如你不想存儲整數(shù),你想存儲字符串,像你的親人名字的集合。我的看起來是這樣的: relatives_names = [ "Toshiaki", "Juliana", "Yuji", "Bruno", "Kaio"] print(relatives_names[4]) # Kaio 它和整型的操作方式一樣。真棒! 我們只是學習索引如何有效使用,但是我仍然需要告訴你我們?nèi)绾螌⒁粋€元素加入數(shù)據(jù)結構(向列表中加入一項)。 bookshelf = [] bookshelf.append("The Effective Engineer") bookshelf.append("The 4 Hour Work Week")print(bookshelf[0]) # The Effective Engineerprint(bookshelf[1]) # The 4 Hour Work Week append超級簡單。你只需要將這個元素當作參數(shù)使用就行(有效的工程師)。這部分足夠了。讓我們談論下一種數(shù)據(jù)結構吧。 by CONFIDANT 05 Dictionary: Key-Value Data StructureNow we know that Let’s learn about the The key is the index pointing to the value. How do we access the I created a As we learned how to access the In the example, I printed a phrase about me using all the values stored in the Another cool thing about Here we have a key (age) value (24) pair using string as the key and integer as the value. As we did with We just need to assign a value to a 字典:鍵值數(shù)據(jù)結構 現(xiàn)在我們都知道,列表以整數(shù)作為索引,但是我們不想用整數(shù)作為索引怎么辦?我們可以使用的數(shù)據(jù)結構有數(shù)值型、字符串型或者是其它索引類型。 dictionary_example = { "key1": "value1", "key2": "value2", "key3": "value3"} 字典是鍵值對的集合,值的索引指向鍵。我們?nèi)绾潍@取字典中的值呢?你猜對了——使用鍵。讓我們一起來試一下: dictionary_tk = { "name": "Leandro", "nickname": "Tk", "nationality": "Brazilian"}print("My name is %s" %(dictionary_tk["name"])) # My name is Leandroprint("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tkprint("And by the way I'm %s" %(dictionary_tk["nationality"])) # And by the way I'm Brazilian 我構造了一個有關于我的字典,包括我的姓名、昵稱和國籍。這些屬性都是字典的鍵。正如我們學過的如何使用索引來獲取列表一樣,我們也使用索引來得到存儲在字典中的值。比如,我輸出一句有關我的語句,而它會用到所有存儲在字典中的屬性。非常簡單,對嗎?還有一件很贊的事,我們可以把任何東西當作值來使用。在我所構造的字典中,我想增加一個鍵“年齡”,而且我的真正的整數(shù)年齡也在里面: dictionary_tk = { "name": "Leandro", "nickname": "Tk", "nationality": "Brazilian", "age": 24}print("My name is %s" %(dictionary_tk["name"])) # My name is Leandroprint("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tkprint("And by the way I'm %i and %s" %(dictionary_tk["age"], dictionary_tk["nationality"])) # And by the way I'm Brazilian 這里,我們有一組鍵(年齡)值(24)對,其中鍵為字符串型,值為整型。和我們用列表做的一樣,讓我們學一下如何向字典中增加元素吧。字典中很大一部分都是鍵指向值。當我們談論向字典中增加元素的時候, dictionary_tk = { "name": "Leandro", "nickname": "Tk", "nationality": "Brazilian"} dictionary_tk['age'] = 24print(dictionary_tk) # {'nationality': 'Brazilian', 'age': 24, 'nickname': 'Tk', 'name': 'Leandro'} 我們只需要給字典中的鍵賦一個值。這里沒有什么是復雜的,對嗎? by CONFIDANT 06 Iteration: Looping Through Data StructuresAs we learned in the Python Basics, the So for each book in the bookshelf, we (can do everything with it) print it. Pretty simple and intuitive. That’s Python. For a hash data structure, we can also use the This is an example how to use it. For each Another way to do it is to use the We did name the two parameters as We can see we used attribute as a parameter for the 循環(huán):通過數(shù)據(jù)結構進行循環(huán) bookshelf = [ "The Effective Engineer", "The 4 hours work week", "Zero to One", "Lean Startup", "Hooked"]for book in bookshelf: print(book) 對于書架上的每本書,我們(可以用它做任何事)將它打印出來。非常簡單直觀,這就是Python。 dictionary = { "some_key": "some_value" }for key in dictionary: print("%s --> %s" %(key, dictionary[key])) # some_key --> some_value 這是一個如何使用的例子。對于字典中的每個鍵,我們都會輸出鍵和與之對應的值。另一種方法是用iteritems方法。我們的確命名兩個參數(shù)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 我們可以把我們使用的屬性看作是字典key的一個參數(shù),而且它可以正常運行。好極了! by CONFIDANT 07 Classes & ObjectsA 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. 類和對象 by CONFIDANT 08 Python Object-Oriented Programming mode: ONPython, as an Object-Oriented programming language, has these concepts: class and object. 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: 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. Here Remember that our vehicle class has four attributes: number of wheels, type of tank, seating capacity, and maximum velocity. We set all these attributeswhen creating a vehicle object. So here, we define our class to receive data when it initiates it: Python的面向對象的編程模式: class Vehicle: pass 我們通過類聲明來定義類——就是這樣,很簡單吧!對象是類的一個實例。我們通過命名類來構造一個實例。 car = Vehicle() print(car) # <__main__.Vehicle instance at 0x7fb1de6c2638> 這里的car就是一個類Vehicle的一個對象(或實例)。記得我們的車輛類有四個屬性:車輪數(shù)、油箱類型、座位數(shù)和最快速度。當我們構造一個車輛對象時就需要設置這些屬性。因此這里,我們需要定義我們的類,當它初始化的時候能夠接收數(shù)據(jù)。 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 by CONFIDANT 09 We use the Four wheels + electric “tank type” + five seats + 250km/hour maximum speed. 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: This is an implementation of two methods: number_of_wheels and set_number_of_wheels. We call it In Python, we can do that using And we can use these methods as attributes: 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 But we can also use methods for other things, like the “make_noise” method. Let’s see it: When we call this method, it just returns a string “VRRRRUUUUM.” 我們會用到init方法。我們稱它為構造方法。因此當我們構造一個車輛實體時,我們可以定義這些屬性。假設我們都喜歡特斯拉模型S,我們想要構造一個這種類型的對象。它是電動的,有四個車輪和五個座位,而且最快速度為250千米/小時(155英里/小時)。讓我們創(chuàng)建一個這種對象: tesla_model_s = Vehicle(4, 'electric', 5, 250) 對所有屬性進行設置:四個輪子+電動“油箱類型”+五個座位+最快速度為250千米/小時。但是我們?nèi)绾潍@取這些屬性的值呢?我們向該對象發(fā)送了一條查詢屬性值的信息,我們稱之為方法,它是對象的行為。讓我們一起來實現(xiàn)吧: 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 包括兩種方法的實現(xiàn):車輪數(shù)和車輪數(shù)的設置。我們稱為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) # 4tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2print(tesla_model_s.number_of_wheels) # 2 這里有點不同于定義方法,方法和屬性的作用一樣。比如,當我們設置新的車輪數(shù)時,我們不會把2作為參數(shù),而是把number_of_wheels的值設為2。這是一種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 def make_noise(self): print('VRUUUUUUUM') 當我們調用這種方法時,它就會返回一串“VRRRRUUUUM”。 tesla_model_s = Vehicle(4, 'electric', 5, 250) tesla_model_s.make_noise() # VRUUUUUUUM by CONFIDANT 10 Encapsulation: Hiding InformationEncapsulation 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 Instance VariablesFor a Python class, we can initialize a Within the constructor method: Here we apply the Within the class: Here, we do not need to apply the Cool. We have now learned that we can use Keeping the There we go. We just set another value ( 封裝:隱藏信息 一個對象的內(nèi)部表示對外界是隱藏的,只有該對象可以聯(lián)系到其內(nèi)部數(shù)據(jù)。首先我們需要理解公有和非公有實例變量和方法如何運行。 公有實例變量 class Person: def __init__(self, first_name): self.first_name = first_name 在結構體方法中,我們用first_name的值作為對公有實例變量的聲明。 tk = Person('TK')print(tk.first_name) # => TK 在類中,我們不需要將first_name作為聲明,而且實例對象會有一個類屬性,并用初始化為TK。 tk = Person() print(tk.first_name) # => TK 很棒!現(xiàn)在我們知道我們可以使用公有實例變量和類屬性。另一件有關于公有部分的有趣的事情是我們可以管理變量的值。那意味著什么?對象可以管理和設置其變量的值。 要記得Person類,我們想給它的first_name設置另一個值: tk = Person('TK') tk.first_name = 'Kaio'print(tk.first_name) # => Kaio 開始了,我們只是把kaio賦給first_name這個實例變量,而且對其值進行了更新。很簡單,因為它是公有變量,所以我們可以這樣做。 by CONFIDANT 11 Non-public Instance VariableWe don’t use the term “private” here, since no attribute is really private in Python (without a generally unnecessary amount of work).?—?PEP 8 As the “‘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. Here’s an example: Did you see the We can access and update it. So we use a method that allows us to do it inside our class definition. Let’s implement two methods ( Now we can update and access
非公有實例變量 這里我們不用“私有”這一術語,因為在Python中不存在真正的私有屬性(一般沒有不必要的工作量)?!狿EP 8 class Person: def __init__(self, first_name, email): self.first_name = first_name self._email = email 你看到email變量了嗎?它顯示了我們?nèi)绾味xnon-public variable: tk = Person('TK', 'tk@mail.com') print(tk._email) # tk@mail.com 我們可以獲得并更新它。Non-public variables僅僅是種習慣,而且應該被當作API的非公有部分。因此我們用一種方法,它允許我們在類內(nèi)對其進行定義。一起來實現(xiàn)以下兩個方法: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 現(xiàn)在我們使用方法可以更新和獲取non-public variables。讓我們一起來看一下: tk = Person('TK', 'tk@mail.com') print(tk.email()) # => tk@mail.comtk._email = 'new_tk@mail.com'print(tk.email()) # => tk@mail.comtk.update_email('new_tk@mail.com') print(tk.email()) # => new_tk@mail.com 1.我們用TK和tk@mail.com對一個新對象的first_name和email進行初始化。 by CONFIDANT 12 Public MethodWith Let’s test it: Great?—?we can use it without any problem. Non-public MethodBut with And now, we’ll try to call this We can access and update it. Here’s an example for how we can use it: Here we have a 公有方法 class Person: def __init__(self, first_name, age): self.first_name = first_name self._age = age def show_age(self): return self._age 讓我們一起來測試一下: tk = Person('TK', 25)print(tk.show_age()) # => 25 棒極了——沒有任何問題! 非公有方法 對于非公有方法,我們不能那樣做。一起來實現(xiàn)一個同樣的Person類,但是現(xiàn)在我們會用下劃線表示non-public method,即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 現(xiàn)在會通過對象來調用這個方法: tk = Person('TK', 25)print(tk._show_age()) # => 25 我們可以獲得它并對其進行更新。Non-public methods僅僅只是個習慣,而且應該當作API的非公有部分。這里有個例子是有關于對它的使用: 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 這里我們有一個public method為show_age,我們的對象(在類外)可以使用它,而_get_age只能在類定義部分使用(在show_age方法中)。再次提醒:這只是習慣問題。 by CONFIDANT 13 Encapsulation SummaryWith encapsulation we can ensure that the internal representation of the object is hidden from the outside. Inheritance: behaviors and characteristicsCertain 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. 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. Our Car class implemented: Once initiated, we can use all In Python, we apply a 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: Beautiful. 封裝總結 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 已經(jīng)實現(xiàn)了我們的汽車類: my_car = Car(4, 5, 250)print(my_car.number_of_wheels)print(my_car.seating_capacity)print(my_car.maximum_velocity) 一旦對其進行初始化,我們就可以使用所構造的所有instance variables。非常棒!在Python中,我們可以將parent class作為child class的一個參數(shù)。一個電動車類可以繼承我們的汽車類。 class ElectricCar(Car): def __init__(self, number_of_wheels, seating_capacity, maximum_velocity): Car.__init__(self, number_of_wheels, seating_capacity, maximum_velocity) 就是這么簡單。我們不需要實現(xiàn)其它任何方法,因為這個類已經(jīng)有了這些方法(繼承了汽車類)。讓我們來證明一下: my_electric_car = ElectricCar(4, 5, 250)print(my_electric_car.number_of_wheels) # => 4print(my_electric_car.seating_capacity) # => 5print(my_electric_car.maximum_velocity) # => 250 非常漂亮! by CONFIDANT 14 That’s it!We learned a lot of things about Python basics:
Congrats! You completed this dense piece of content about 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基礎,我們已經(jīng)學了很多: ·Python的變量如何工作 ·Python條件聲明如何實現(xiàn) ·Python循環(huán)如何實現(xiàn) ·如何使用List:Collection|Array ·字典鍵值對集合 ·如何利用這些數(shù)據(jù)結構實現(xiàn)循環(huán) ·對象和類 ·屬性作為對象的數(shù)據(jù) ·方法作為對象的行為 ·使用Python的getters和setters和property裝飾器 ·封裝:隱藏信息 ·繼承:行為和特性 祝賀你!你已經(jīng)完成了有關Python的難理解的部分。 如果你想學習完整的Python課程,學習更多的編程技巧和項目搭建,建議試一下One Month Python Bootcamp部分 by CONFIDANT 15 For more stories and posts about my journey learning & mastering programming, follow my publication The Renaissance Developer. Have fun, keep learning, and always keep coding. My Instagram, Twitter, Github & LinkedIn. ? 有關我的日志學習和編程掌握的更多故事和帖子,可以關注我所發(fā)布的The Renaissance Developer。 玩的開心,繼續(xù)學習并保持編程! 我的Instagram,Twitter,GithubLinkdle。
|
|