#daysofMiva의 날 || Python 모듈, JSON, 수학 및 날짜 마스터하기

王林
풀어 주다: 2024-09-07 14:30:32
원래의
326명이 탐색했습니다.

Day of #daysofMiva || Mastering Python Modules, JSON, Math, and Dates

오늘은 #14일이고 플라스크로 달려가기 전에 간단한 Python 프로젝트를 떠났던 곳으로 돌아왔습니다. ㅋㅋㅋ! 코딩은 흥미롭기도 하고 때로는 좌절스럽기도 합니다(또는 대부분의 경우...). 어쨌든, 당신은 경험을 통해 더 잘 알고 있습니다. 그래서 나는 내 것을 기록하는 것을 기쁘게 생각합니다. 그래서 오늘은 Python 모듈, 다형성, JSON, 수학, 날짜/시간, 범위 및 반복자를 배웠습니다. 뛰어들어 보세요.

1. Python 모듈: 재사용 가능한 코드 라이브러리 구축

Python의 모듈은 다양한 스크립트나 프로젝트에서 재사용할 수 있는 Python 코드(함수, 변수 또는 클래스)가 포함된 파일입니다. 모듈을 생성하면 코드 재사용이 촉진되어 프로젝트가 더욱 깔끔하고 모듈화됩니다.

모듈 생성 및 가져오기:

모듈은 단순히 .py 확장자로 저장된 Python 파일입니다. 한 모듈에서 함수, 변수, 클래스를 정의하고 이를 다른 모듈로 가져올 수 있습니다.

예: 모듈 생성 및 사용

  1. 다음 내용으로 mymodule.py라는 파일을 만듭니다.
# mymodule.py
def greeting(name):
    print(f"Hello, {name}")
로그인 후 복사
  1. 이제 다른 Python 스크립트에서 모듈을 가져옵니다.
import mymodule

mymodule.greeting("Jonathan")  # Output: Hello, Jonathan
로그인 후 복사

가져올 때 모듈에 별칭을 지정할 수도 있습니다.

import mymodule as mx

mx.greeting("Jane")  # Output: Hello, Jane
로그인 후 복사

내장 모듈 사용:

Python에는 다양한 모듈이 내장되어 있습니다. 예를 들어 플랫폼 모듈을 사용하여 시스템 정보를 검색할 수 있습니다.

import platform

print(platform.system())  # Output: The OS you're running (e.g., Windows, Linux, etc.)
로그인 후 복사

2. Python에서 JSON 작업: JSON 데이터 구문 분석 및 생성

JSON(JavaScript Object Notation)은 웹 애플리케이션에서 데이터를 전송하는 데 널리 사용됩니다. Python은 JSON을 구문 분석하고 생성하는 json 모듈을 제공합니다.

JSON 구문 분석:

json.loads()를 사용하여 JSON 문자열을 Python 사전으로 변환할 수 있습니다.

import json

json_data = '{ "name": "John", "age": 30, "city": "New York" }'
parsed_data = json.loads(json_data)

print(parsed_data['age'])  # Output: 30
로그인 후 복사

Python 객체를 JSON으로 변환:

json.dumps()를 사용하여 Python 객체(예: dict, list, tuple)를 JSON 문자열로 변환할 수도 있습니다.

예:

import json

python_obj = {"name": "John", "age": 30, "city": "New York"}
json_string = json.dumps(python_obj)

print(json_string)  # Output: {"name": "John", "age": 30, "city": "New York"}
로그인 후 복사

JSON 출력 형식 지정 및 사용자 정의:

indent 매개변수를 사용하면 JSON 문자열을 더 읽기 쉽게 만들 수 있습니다.

json_string = json.dumps(python_obj, indent=4)
print(json_string)
로그인 후 복사

이렇게 하면 올바른 형식의 JSON 문자열이 출력됩니다.

{
    "name": "John",
    "age": 30,
    "city": "New York"
}
로그인 후 복사

3. Python 수학: 수학 연산 수행

Python은 다양한 수학 작업을 수행하기 위한 내장 함수와 수학 모듈을 모두 제공합니다.

기본 수학 함수:

min() 및 max(): iterable에서 최소값과 최대값을 찾으려면:

print(min(5, 10, 25))  # Output: 5
print(max(5, 10, 25))  # Output: 25
로그인 후 복사

abs(): 숫자의 절대값을 반환합니다.

print(abs(-7.25))  # Output: 7.25
로그인 후 복사

pow(): 숫자의 거듭제곱을 계산합니다.

print(pow(4, 3))  # Output: 64 (4 to the power of 3)
로그인 후 복사

수학 모듈:

고급 수학 연산을 위해 수학 모듈은 광범위한 기능 세트를 제공합니다.

  • 제곱근: math.sqrt() 사용:
import math

print(math.sqrt(64))  # Output: 8.0
로그인 후 복사
  • 천장 및 바닥: 숫자를 올림 또는 내림:
print(math.ceil(1.4))  # Output: 2
print(math.floor(1.4))  # Output: 1
로그인 후 복사
  • PI 상수: π 값에 액세스:
print(math.pi)  # Output: 3.141592653589793
로그인 후 복사

4. 날짜 작업: Python에서 시간 관리

Python의 datetime 모듈은 날짜와 시간을 관리하는 데 도움이 됩니다. 현재 날짜를 생성하거나, 특정 구성 요소(예: 연, 월, 일)를 추출하거나 날짜 개체를 조작할 수 있습니다.

현재 날짜 및 시간 가져오기:

datetime.now() 함수는 현재 날짜와 시간을 반환합니다.

import datetime

current_time = datetime.datetime.now()
print(current_time)
# Output: 2024-09-06 05:15:51.590708 (example)
로그인 후 복사

구체적인 날짜 설정:

datetime() 생성자를 사용하여 사용자 정의 날짜를 만들 수 있습니다.

custom_date = datetime.datetime(2020, 5, 17)
print(custom_date)  # Output: 2020-05-17 00:00:00
로그인 후 복사

strftime()을 사용하여 날짜 형식 지정:

strftime()을 사용하여 날짜 객체의 형식을 문자열로 지정할 수 있습니다.

예:

formatted_date = custom_date.strftime("%B %d, %Y")
print(formatted_date)  # Output: May 17, 2020
로그인 후 복사

다음은 strftime()에서 사용되는 몇 가지 일반적인 형식 코드 표입니다.

Directive Description Example
%a Short weekday Wed
%A Full weekday Wednesday
%b Short month name Dec
%B Full month name December
%Y Year (full) 2024
%H Hour (24-hour format) 17
%I Hour (12-hour format) 05

Polymorphism in Python

Polymorphism refers to the ability of different objects to be treated as instances of the same class through a common interface. It allows methods to do different things based on the object it is acting upon.

Method Overriding
In Python, polymorphism is often achieved through method overriding. A subclass can provide a specific implementation of a method that is already defined in its superclass.

Example:

class Animal:
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        return "Woof!"

class Cat(Animal):
    def make_sound(self):
        return "Meow!"

# Using polymorphism
def animal_sound(animal):
    print(animal.make_sound())

dog = Dog()
cat = Cat()

animal_sound(dog)  # Output: Woof!
animal_sound(cat)  # Output: Meow!
로그인 후 복사

In the above example, animal_sound() can handle both Dog and Cat objects because they both implement the make_sound() method, demonstrating polymorphism.

Operator Overloading

Polymorphism also allows you to define how operators behave with user-defined classes by overloading them.

Example:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(2, 3)
v2 = Vector(4, 1)
v3 = v1 + v2

print(v3)  # Output: Vector(6, 4)
Here, the + operator is overloaded to handle Vector objects, allowing us to add vectors using the + operator.

2. Iterators in Python
An iterator is an object that allows you to traverse through a container, such as a list or tuple, and retrieve elements one by one. Python iterators implement two main methods: __iter__() and __next__().

Creating an Iterator
You can create your own iterator by defining a class with __iter__() and __next__() methods.

Example:

python
Copy code
class CountDown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.start <= 0:
            raise StopIteration
        current = self.start
        self.start -= 1
        return current

# Using the iterator

cd = CountDown(5)
for number in cd:
    print(number)
# Output: 5, 4, 3, 2, 1
로그인 후 복사

In this example, CountDown is an iterator that counts down from a starting number to 1.

Using Built-in Iterators
Python provides built-in iterators such as enumerate(), map(), and filter().

Example:

numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)

for num in squared:
    print(num)
# Output: 1, 4, 9, 16, 25
로그인 후 복사

Here, map() applies a function to all items in the list and returns an iterator.

Scope in Python

Scope determines the visibility of variables in different parts of the code. Python uses the LEGB rule to resolve names: Local, Enclosing, Global, and Built-in.

Local Scope

Variables created inside a function are local to that function.

Example:

def my_func():
    x = 10  # Local variable
    print(x)

my_func()
# Output: 10
로그인 후 복사

Here, x is accessible only within my_func().

Global Scope

Variables created outside any function are global and accessible from anywhere in the code.

Example:

Copy code
x = 20  # Global variable

def my_func():
    print(x)

my_func()
print(x)
# Output: 20, 20
로그인 후 복사

Enclosing Scope

In nested functions, an inner function can access variables from its enclosing (outer) function.

Example:

def outer_func():
    x = 30

    def inner_func():
        print(x)  # Accessing variable from outer function

    inner_func()

outer_func()
# Output: 30
로그인 후 복사

Global Keyword

To modify a global variable inside a function, use the global keyword.

Example:

x = 50

def my_func():
    global x
    x = 60

my_func()
print(x)
# Output: 60
로그인 후 복사

Nonlocal Keyword

The nonlocal keyword allows you to modify a variable in the nearest enclosing scope that is not global.

Example:

def outer_func():
    x = 70

    def inner_func():
        nonlocal x
        x = 80

    inner_func()
    print(x)

outer_func()
# Output: 80
로그인 후 복사

In this example, nonlocal allows inner_func() to modify the x variable in outer_func().

Check out my #100daysofMiva repo on GitHub. Follow, Star and Share.

위 내용은 #daysofMiva의 날 || Python 모듈, JSON, 수학 및 날짜 마스터하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!