Python 배우기 : 0에서 영웅으로

우선, 파이썬이란 무엇입니까? 제작자 Guido van Rossum에 따르면 Python은 다음과 같습니다.

"고수준 프로그래밍 언어와 핵심 디자인 철학은 모두 코드 가독성과 프로그래머가 몇 줄의 코드로 개념을 표현할 수있는 구문에 관한 것입니다."

저에게 파이썬을 배워야하는 첫 번째 이유는 그것이 사실 아름다운프로그래밍 언어. 코드를 작성하고 내 생각을 표현하는 것은 정말 자연스러운 일이었습니다.

또 다른 이유는 데이터 과학, 웹 개발 및 기계 학습이 모두 여기에서 빛을 발하는 등 다양한 방법으로 Python에서 코딩을 사용할 수 있기 때문입니다. Quora, Pinterest 및 Spotify는 모두 백엔드 웹 개발에 Python을 사용합니다. 그래서 그것에 대해 조금 배우자.

기초

1. 변수

변수는 값을 저장하는 단어로 생각할 수 있습니다. 그렇게 간단합니다.

파이썬에서는 변수를 정의하고 값을 설정하는 것이 정말 쉽습니다. "one"이라는 변수에 숫자 1을 저장한다고 상상해보십시오. 해보자 :

one = 1

얼마나 간단 했나요? 변수 "one"에 값 1을 할당했습니다.

two = 2 some_number = 10000

그리고 원하는 다른 변수에 다른 을 할당 할 수 있습니다 . 위의 표에서 볼 수 있듯이 변수 " two "는 정수 2를 저장 하고 " some_number "는 10,000을 저장 합니다.

정수 외에도 부울 (True / False), 문자열, 부동 및 기타 여러 데이터 유형을 사용할 수 있습니다.

# booleans true_boolean = True false_boolean = False # string my_name = "Leandro Tk" # float book_price = 15.80

2. 제어 흐름 : 조건문

" If "는 표현식을 사용하여 문이 참인지 거짓인지 평가합니다. True이면 "if"문 안에있는 것을 실행합니다. 예를 들면 :

if True: print("Hello Python If") if 2 > 1: print("2 is greater than 1")

21 보다 크므로 " 인쇄 "코드가 실행됩니다.

" if "표현식이 거짓 이면 " else "문이 실행됩니다 .

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

12 보다 크지 않으므로 " 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. 루핑 / 반복자

파이썬에서는 다른 형태로 반복 할 수 있습니다. 나는이 얘기하자 : 동안에 대한 .

While Looping : 문이 True 인 동안 블록 내부의 코드가 실행됩니다. 따라서이 코드는 1 에서 10 까지의 숫자를 인쇄합니다 .

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

동안의 루프는 "필요 루프 조건을. ”True로 유지되면 계속 반복됩니다. 이 예에서는 언제 num이며 루프 조건 같음 .11False

더 잘 이해하기위한 또 다른 기본 코드 :

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

루프 조건 입니다 True그것이 반복하는 유지 - 그래서 우리가로 설정 될 때까지 False.

For Looping : 변수“ num ”을 블록에 적용하면 “ for ”문이이를 반복합니다. 이 코드는 while 코드 와 동일하게 인쇄됩니다 : from 1 ~ 10 .

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

보다? 너무 간단합니다. 범위는로 시작 1하여 11th 요소 ( 1010th 요소) 까지갑니다 .

목록 : 컬렉션 | 어레이 | 데이터 구조

정수 1을 변수에 저장한다고 상상해보십시오. 하지만 이제 2를 저장하고 싶을 수도 있습니다. 그리고 3, 4, 5…

내가 원하는 모든 정수를 저장하는 다른 방법이 있지만 수백만 개의 변수가 아닌가? 짐작하셨습니다. 실제로 저장하는 또 다른 방법이 있습니다.

List값 목록을 저장하는 데 사용할 수있는 컬렉션입니다 (예 : 원하는 정수). 그래서 그것을 사용합시다 :

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

정말 간단합니다. 배열을 만들어 my_integer에 저장했습니다 .

그러나 아마도 "이 배열에서 값을 어떻게 얻을 수 있습니까?"라고 질문 할 수 있습니다.

좋은 질문입니다. indexList 라는 개념이 있습니다. 첫 번째 요소는 인덱스 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

정수와 같은 방식으로 작동합니다. 좋은.

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).

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

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.

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

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.

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

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

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

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 Dictionarykeys.

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.

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

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

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.

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

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 Dictionarykey. Nothing complicated here, right?

Iteration: Looping Through Data Structures

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

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.

For a hash data structure, we can also use the for loop, but we apply the 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.

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

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:

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 Dictionarykey, and it works properly. Great!

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 Object-Oriented Programming mode: ON

Python, 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:

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) # 

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

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 initmethod. 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:

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

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:

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.

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

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 pythonicgetter and setter code.

But we can also use methods for other things, like the “make_noise” method. Let’s see 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 make_noise(self): print('VRUUUUUUUM')

이 메서드를 호출하면 문자열 " VRRRRUUUUM.

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

캡슐화 : 정보 숨기기

캡슐화는 개체의 데이터 및 메서드에 대한 직접 액세스를 제한하는 메커니즘입니다. 그러나 동시에 해당 데이터 (객체의 메서드)에 대한 작업을 용이하게합니다.

“캡슐화를 사용하여 데이터 멤버 및 멤버 기능을 숨길 수 있습니다. 이 정의에서 캡슐화는 객체의 내부 표현이 일반적으로 객체의 정의 외부에서 보이지 않도록 숨겨져 있음을 의미합니다.” — 위키 백과

개체의 모든 내부 표현은 외부에서 숨겨집니다. 개체 만 내부 데이터와 상호 작용할 수 있습니다.

첫째, 우리는 어떻게 이해해야 public하고 non-public예 변수와 메소드의 작업을.

공용 인스턴스 변수

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

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.

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.

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.

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

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

우리는 거기에 갈. 인스턴스 변수에 다른 값 ( kaio)을 설정 first_name하고 값을 업데이트했습니다. 그렇게 간단합니다. public변수 이기 때문에 할 수 있습니다.

비공개 인스턴스 변수

여기서는 "private"라는 용어를 사용하지 않습니다. 왜냐하면 파이썬에서는 어떤 속성도 실제로 사적인 것이 아니기 때문입니다 (일반적으로 불필요한 작업량없이). — PEP 8

으로 생성자 메서드 또는 클래스 내에서 둘 다 public instance variable정의 할 수 있습니다 non-public instance variable. 구문 차이 :의 경우 이름 앞에 non-public instance variables밑줄 ( _)을 사용합니다 variable.

객체 내부에서만 접근 할 수없는“ 'Private'인스턴스 변수는 파이썬에 존재하지 않습니다. 그러나 대부분의 Python 코드가 따르는 규칙이 있습니다. 밑줄 (예 :)이 붙은 이름 _spam은 API의 비공개 부분으로 처리해야합니다 (함수, 메서드 또는 데이터 멤버 여부).” — Python 소프트웨어 재단

예를 들면 다음과 같습니다.

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

email변수를 보았습니까 ? 이것이 우리가 정의하는 방법입니다 non-public variable.

tk = Person('TK', '[email protected]') print(tk._email) # [email protected]
우리는 그것을 액세스하고 업데이트 할 수 있습니다. Non-public variables관례 일 뿐이며 API의 비공개 부분으로 취급해야합니다.

그래서 우리는 클래스 정의 내에서 그것을 할 수있는 방법을 사용합니다. 이를 이해하기 위해 두 가지 메서드 ( 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

이제 non-public variables이러한 방법을 사용하여 업데이트하고 액세스 할 수 있습니다 . 보자 :

tk = Person('TK', '[email protected]') print(tk.email()) # => [email protected] # tk._email = '[email protected]' -- treat as a non-public part of the class API print(tk.email()) # => [email protected] tk.update_email('[email protected]') print(tk.email()) # => [email protected]
  1. We initiated a new object with first_name TK and email [email protected]
  2. Printed the email by accessing the non-public variable with a method
  3. Tried to set a new email out of our class
  4. We need to treat non-public variable as non-public part of the API
  5. Updated the non-public variable with our instance method
  6. Success! We can update it inside our class with the helper method

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

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_agenon-public method using an underscore (_).

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:

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

여기에 _get_agenon-public methodshow_agepublic method. 는 show_age우리의 객체 (클래스 외부)에서 사용할 수 있으며 _get_age클래스 정의 (내부 show_age메서드) 내에서만 사용할 수 있습니다 . 그러나 다시 : 관습의 문제로.

캡슐화 요약

캡슐화를 통해 객체의 내부 표현이 외부에서 숨겨 지도록 할 수 있습니다.

상속 : 행동 및 특성

특정 객체에는 공통점이 있습니다. 행동과 특성입니다.

예를 들어, 저는 아버지로부터 몇 가지 특성과 행동을 물려 받았습니다. 나는 그의 눈과 머리카락을 특징으로, 그의 조바심과 내향성을 행동으로 물려 받았습니다.

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 anElectricCar class inherits these same attributes from the regular Car class.

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)

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

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

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:

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:

  • How Python variables work
  • How Python conditional statements work
  • How Python looping (while & for) works
  • 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
  • Encapsulation: hiding information
  • Inheritance: behaviors and characteristics

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 ☺

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 Twitter & Github. ☺