StoryCode

기본문법

Python, 파이썬
반응형

기본문법 참조 1) https://wikidocs.net/20

추가 참조 2) https://ssungkang.tistory.com/entry/%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EC%9D%B8%EC%8A%A4%ED%84%B4%EC%8A%A4%EB%9E%80-3-%EB%A9%94%EC%86%8C%EB%93%9C?category=310107



데이타 타입

 

 

True / False
참조) https://edykim.com/ko/post/python-list-vs.-tuple/

List = [1, 2, 3]
Tuple = ( 1, 2, 3 )
# 둘의 차이는 List 는 가변적, 튜플은 불변적이다.
# List[1] = "two" 를 하면 결과 [ 1, 'two', 3 ] 이 출력된다.
# Tuple[1] = "two" 하면 오류가 난다.
# 즉 List 에는 .append() 할 수 있지만, Tuple 은 안된다.

dict 타입)
mydata = {
    "name" : "hongildong",
    "info" : [
        "address":"seoul",
        "age" : "30"
    ]
}

dict => json string

myjson = json.dumps(mydata)

x = (1,2,3)

print (1 in x) # True

print (2 in x) # False

fruit = ["사과", "사과", "바나나", "사과", "사과", "바나나", "사과", "사과","바나나", "복숭아"]
countfruit = {}

for fruitname in fruit:
    if fruitname in countofruit:
        countfruit[ fruitname ] = countfruit[ fruitname ]+1
    else:
        countfruit[ fruitname ] = 1

print (d)


# {'사과':5, '바나나':3, '복숭아':1}

기본 문장

1)
money = 1000
if money >= 10000:
   print ("Yes")
else:
   print("No")

2)
if money >= 100 and money <= 10000 or money == 0:
if not 0:

if 1 in [1,2,3]

if a in ('a', 'b', 'c')

3)
message = "success" if score >= 60 else "failure"

변수 스코프

Local   :   함수 내부의 공간
Enclosing Function Local   :  함수를 내포하는 또 다른 함수의 공간
Global   :   함수 외부의 공간
Built-in   :   내장영역

x = 10
y = 20
def outer():
    x = 11
    def inner():
        z = 30
        print(x,y,z)
    inner()
    x = 40
    inner()
    global y
    y = 30


outer()
print (x)
print (y)

# 11 20 30
# 40 20 30
# 10
# 30

 정규식

https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace 
# 양쪽 공백 제거
s = " \t a string example\t "
s = s.strip()

# 오른쪽 공백 제거
s = s.rstrip()

# 왼쪽 공백 제거
s = s.lstrip()

# 정규식
import re
pat = re.compile(r'\s+')
s = '   \t   foo   \t   bar   \t   '
print pat.sub('', s) # prints "foobar"

출처: https://bluesid.tistory.com/337 [기록, 정리 조각]
Class 정의 class Human():
    def __init__(self):
        print("초기화 함수가 실행되었습니다.")

    def __str__(self): # to_string()
        return "현재 {}의 나이는 {}세 입니다.".format(self.job,self.age)

    def define_Human(job,age):
        person = Human()
        person.job = job
        person.age = age
        return person
 
    def get_older(self):
        self.age += 1
        print("{}의 나이가 {}가 되었습니다".format(self.job,self.age))

    def speak(self, message):
        print(message)

class Police(Human):
    def arrest(self, tohuman):
       print("체포 : " + tohuman)

person = Human.define_Human('student',23)
arrestperson = Police()



#person.get_older() # student의 나이가 24가 되었습니다

Package

 

# Package 는 directory 다.

main.py

> animal
   __init__.py : Package 에 들어있어야 하는 필수 파일이다. 내용으로 from class명 import funcion명
   cat.py  : cat class 파일이다.
   dog.py : dog class 파일이다.


참조) animal.__init__py 의 내용
from .cat import Cat
from .dog import Dog

Static method
Instance Method
Class

Meta Class

 
Static Method : 일반적인 Class 의 Static Method
Instance Method : 일반적인 Instance Method
Class : 일반적인 Class

Meta Class : 동적 클래스 생성. API 제작용. 파이썬에서는 클래스 자체가 객체이며, 클래스를 만드는 역할이 메타 클래스. Type = 'type'.

Meta Class 추가설명 참조 : https://dojang.io/mod/page/view.php?id=2468

선언 방법 예 1)
myClass = type('myClass', (), '{'a':True}}

* 위 문장은 아래 클래스 정의와 같다.
class myClass(object):
    a = True

선언후 클래스 할당1)
    myclassinstance = myClass()






선언 방법 예 2)
def replace(self, old, new):    # 클래스에 들어갈 메서드 정의
    while old in self:
        self[self.index(old)] = new
 
# list를 상속받음, 속성 desc, 메서드 replace 추가
AdvancedList = type('AdvancedList', (list, ), { 'desc': '향상된 리스트', 'replace': replace })
 
x = AdvancedList([1, 2, 3, 1, 2, 3, 1, 2, 3])
x.replace(1, 100)
print(x)         # [100, 2, 3, 100, 2, 3, 100, 2, 3]
print(x.desc)    # 향상된 리스트





선언 방법 예 3) 클래스가 type 을 상속 받으면 메타 클래스가 된다. Ex> class metaclass(type):
class MakeCalc(type):    # type을 상속받음
    def __new__(metacls, name, bases, namespace):      # 새 클래스를 만들 때 호출되는 메서드
        namespace['desc'] = '계산 클래스'              # 새 클래스에 속성 추가
        namespace['add'] = lambda self, a, b: a + b    # 새 클래스에 메서드 추가
        return type.__new__(metacls, name, bases, namespace)    # type의 __new__ 호출
 
Calc = MakeCalc('Calc', (), {})    # 메타클래스 MakeCalc로 클래스 Calc 생성
c = Calc()                         # 클래스 Calc로 인스턴스 c 생성
print(c.desc)                      # '계산 클래스': 인스턴스 c의 속성 출력
print(c.add(1, 2))                 # 3: 인스턴스 c의 메서드 호출







활용)
class Singleton(type):    # type을 상속받음
    __instances = {}      # 클래스의 인스턴스를 저장할 속성
    def __call__(cls, *args, **kwargs):    # 클래스로 인스턴스를 만들 때 호출되는 메서드
        if cls not in cls.__instances:     # 클래스로 인스턴스를 생성하지 않았는지 확인
            cls.__instances[cls] = super().__call__(*args, **kwargs)
                                           # 생성하지 않았으면 인스턴스를 생성하여 속성에 저장
        return cls.__instances[cls]        # 클래스로 인스턴스를 생성했으면 인스턴스 반환
 
class Hello(metaclass=Singleton):    # 메타클래스로 Singleton을 지정
    pass
 
a = Hello()     # 클래스 Hello로 인스턴스 a 생성
b = Hello()     # 클래스 Hello로 인스턴스 b 생성
print(a is b)   # True: 인스턴스 a와 b는 같음
언패킹 ( Unpacking ) Case 1)
def mysum(a,b):
    result = a+b
    return result

mylist = [3,5]

print(mysum(*mylist)) # 8
Case 2)
def mysum(*args):
    result = 0
    for num in args:
        result = result + num
    return result

mylist = [3,5,7]

print(mysum(*mylist)) # 15
키워드 인수 def subject(math, english, korean):
    print('수학 성적: ', math)
    print('영어 성적: ', english)
    print('국어 성적: ', korean)

subject(90,85,70)subject(90,85,70)
#수학 성적:  90
#영어 성적:  85
#국어 성적:  70

subject(english=85,korean=70,math=90)
#수학 성적:  90
#영어 성적:  85
#국어 성적:  70
"딕셔너리 + 키워드 인수" 언패킹 def subject(math, english, korean):
    print('수학 성적: ', math)
    print('영어 성적: ', english)
    print('국어 성적: ', korean)

myscore = {'english': 85, 'korean': 70, 'math': 90}
subject(**myscore)
#수학 성적:  85  
#영어 성적:  70  
#국어 성적:  90

-------------------------------------------------------------------------

def subject(math, english, korean):
    print('수학 성적: ', math)
    print('영어 성적: ', english)
    print('국어 성적: ', korean)

myscore = {'english': 85, 'korean': 70, 'math': 90}
subject(*myscore)
#수학 성적:  english
#영어 성적:  korean
#국어 성적:  math

-------------------------------------------------------------------------

def subject(**kwargs):
    for key,value in kwargs.items():
        print(key+' 성적: ', value)


myscore = {'english': 85, 'korean': 70, 'math': 90}
subject(**myscore)
@decorator

데코레이터

https://ssungkang.tistory.com/entry/python-%EC%9E%A5%EC%8B%9D%EC%9E%90-%EB%8D%B0%EC%BD%94%EB%A0%88%EC%9D%B4%ED%84%B0decorator-%EB%A5%BC-%EC%95%8C%EC%95%84%EB%B3%B4%EC%9E%90?category=310107

문자열함수 a = "ssungkang"
 
print (a.index("k")) # 5
print (a.find("k"))  # 5
print (a.index("x")) # error
print (a.find("x"))  # -1
자료 처리.map test = [1,2,3,4]
 
def func(x):
    return x * 2
 
print(list(map(func, test)))
 
# [2, 4, 6, 8]
자료 처리.String.문자열.Character split test = input().split()
print(test)
#['1', '2', '3', '4']

for i in range(len(test)):
    test[i] = int(test[i])
print(test)
# [1, 2, 3, 4]


위 두 문장을 하나로 합치면,
test = list(map(int, input().split()))
print(test)
# [1, 2, 3, 4]
외부 모듈 사용하기

Ex>

cmd> pip install geopy

 

python>

import from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="wonie")
location = geolocator.geocode("175 5th Avenue NYC")
print (location)

반응형

'Python, 파이썬' 카테고리의 다른 글

DJango.ORM  (0) 2020.02.12
Django Rest FrameWork  (0) 2020.02.07
DJango (Windows)  (0) 2020.01.31
설치.DJango + Redis + Celery  (0) 2020.01.29
설치.Windows10.Request Module  (0) 2019.08.06