StoryCode

'분류 전체보기'에 해당되는 글 563건

  1. 마우스 하나로 두대 컴퓨터.Synergy
  2. 디렉토리검색
  3. Hoisting.호이스팅
  4. DJango 의 장점
  5. DJango.ORM
  6. IOT (Indexed Organized Table)
  7. NESTED TABLE Column
  8. Javascript.Hoisting
  9. Django Rest FrameWork
  10. 기본문법

마우스 하나로 두대 컴퓨터.Synergy

사무, 유용한 툴
반응형

synergy-1.5.0-r2278-Windows-x64.msi
8.14MB
synergy-1.5.0-r2278-Windows-x86.msi
8.02MB

 

1) synergy-1.5.0-r2278-Windows-x64.msi 를 두 컴퓨터에 모두 설치

 

2) 마우스가 연결된 컴퓨터가 "서버"가 된다.

[ Configure Server ] 버튼을 클릭하면 아래와 같은데,

 

우측 상단의 컴퓨터 아이콘을 드래그앤드랍해서 원하는 곳에 놓는다.

아이콘을 더블 클릭해서 Screen name 부분에 Cline 의 아이피를 입력해야 접속 허가가 된다.

OK 버튼을 누르면 아래와 같이 된다.

 

3) 마우스가 없는 컴퓨터가 "클라이언트" 다.

아래처럼 아이피를 입력하고 [Start] 버튼을 클릭하면 설정 끝이고, 클라이언트에 마우스를 제어할 수 있게 된다.

반응형

'사무, 유용한 툴' 카테고리의 다른 글

ZOOM.iPad 미러링  (0) 2020.04.02
ZOOM.사전 등록.출석  (0) 2020.04.02
삼성브라우저에서 계속 문제 발생  (0) 2018.05.29
판서, 전자칠판, EpicPen  (0) 2018.05.29
팀뷰 리셋, TeamViewer Reset  (0) 2017.04.19

디렉토리검색

Python, 파이썬
반응형

참조) https://wikidocs.net/39

 

import os

def search(dirname):
    try:
        filenames = os.listdir(dirname)
        for filename in filenames:
            full_filename = os.path.join(dirname, filename)
            if os.path.isdir(full_filename):
                search(full_filename)
            else:
                ext = os.path.splitext(full_filename)[-1]
                if ext == '.py': 
                    print(full_filename)
    except PermissionError:
        pass

search("c:/")

 

 

혹은

 

 

 

import os

for (path, dir, files) in os.walk("c:/"):
    for filename in files:
        ext = os.path.splitext(filename)[-1]
        if ext == '.py':
            print("%s/%s" % (path, filename))

 

 

 

반응형

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

아래한글 ( HWP ) 텍스트 처리  (0) 2020.02.17
DJango Debug Toolbar  (0) 2020.02.17
DJango 의 장점  (0) 2020.02.12
DJango.ORM  (0) 2020.02.12
Django Rest FrameWork  (0) 2020.02.07

Hoisting.호이스팅

JavaScript, ECMAScript
반응형

참조) https://gmlwjd9405.github.io/2019/04/22/javascript-hoisting.html

Compile Phase 1 에서 선언이 필요한 부분을 검색하는 것을 말한다.

 

Hoisting 대상

1. var 변수 선언

2. 함수 선언문

Hoisting 비 대상

1. let 변수 선언

2. 함수 표현식

var variable = "Yes"; let variable = "Yes";
# 함수 선언문
function func()
{
}
# 함수 표현식
var foo2 = function()
{
}
   
   
   
   
반응형

'JavaScript, ECMAScript' 카테고리의 다른 글

자바스크립트 역사.  (0) 2020.09.21
Count, 카운트  (0) 2020.03.09
실수를 정수로 바꾸는 방법  (0) 2020.03.04
자바스크립트.변수.모니터링워처  (0) 2020.02.01
한글 받침 구별법  (0) 2019.04.15

DJango 의 장점

Python, 파이썬
반응형

참조) https://blog.lxf.kr/2018-11-19---why-or-not-django/

 

 

기본 Admin 페이지 제공  
기본 보안 CSRF
편한 개발/디버깅  
각종 플러그인 RESTful, 캐싱, 이미지변환, CDN 지원
성능 느린편이나 확장이 용이.
반응형

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

DJango Debug Toolbar  (0) 2020.02.17
디렉토리검색  (0) 2020.02.13
DJango.ORM  (0) 2020.02.12
Django Rest FrameWork  (0) 2020.02.07
기본문법  (0) 2020.02.06

DJango.ORM

Python, 파이썬
반응형

참조) https://www.slideshare.net/EunhyangKim2/ss-118560530

# 앞 부분만 정리.

포스트 다 가져오기 Post.objects.all()
포스트 1개 가져오기 Post.objects.get(id=1)
내가 쓴 포스트 가져오기 Post.objects.filter(username="hyang")

 

머신 러닝 모델의 여러 버전마다 실행된 것들에서 8월 1일에서 8월20일까지 실행된 것 들 중 error 없이 실행된 active 한 것들만 모아서, 응답시간의 평균값, 최대값, 그리고 모델에 설정한 스레숄드 값보다 빠르게 응답한 개수 가져오기
#머신 러닝 모델의 여러 버전마다 실행된 것들에서 8월 1일에서 8월20일까지 실행된 것 들 중 error 없이 실행된 active 한 것들만 모아서
run_qs = Run.objects.filter(
    version__id__in=version_ids,
    ml_model__id__in=version_ids,
    is_active=True
    requested_at__range=(start_date, end_date)
)
# 응답시간의 평균값, 최대값
run_qs.aggregate(Avg('response_time'), Max('response_time'))
# 그리고 모델에 설정한 스레숄드 값보다 빠르게 응답한 개수 가져오기
run.response_time > ml_model.threshold인 run 의 총개수 ?
특정기준으로 값을 묶어 새로운 컬럼 만들때는 annotation!

run_qs.annotate(
    fast_runs=Count(
        Case(
               When(response_time__gt=F('ml_model_threshold'), then=1), output_field=IntegerField(),
        )
    )
).aggregate(Sum('fast_runs'))

 

ForeignKey select_related
ManyToManyField preFetch_related
# select_related : 데이타는 한꺼번에 가져와야 한다.
class Post(models.Model):
    author = models.ForeignKey(Author)
    tag = models.ManyToManyField(Tag)

1) 아래 경우는 각 문장이 각각 한번씩 query 해서 두번 가져온다.
post = Post.objects.get(id=1)
author = post.author

2) 위를 한번에 가져오려면 아래와 같이 변경한다.
post = Post.objects.select_related('author').get(id=1)
author = post.author
# prefetch_related : 
1) 아래 경우는 post 하나 돌때마다 가져온다.
posts = Post.objects.all()
for post in posts:
    for tag in post.tag_set.all():
        print(tag)

2) posts = Post.objects.all().prefetch_related('tag_set')
for post in posts:
    for tag in post.tag_set.all():
        print(tag)
# 불필요한 컬럼은 다 가져오지 않는다.
posts = Post.objects.values('name')
for post in posts:
    print(post.name)
# 필요한 것만 가져오기
1) 아래 경우는 If posts: 문장이 모든 데이타를 다 가져온다.
posts = Post.objects.all()
If posts: #
   print(posts)

2) 이를 아래와 바꾸는 것이 좋다.
If posts.exists()

 

참고 ) Django-debug-toolbar 에서 ORM 이 실제 쿼리를 어떻게 날렸는지 확인가능하다.

 

반응형

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

디렉토리검색  (0) 2020.02.13
DJango 의 장점  (0) 2020.02.12
Django Rest FrameWork  (0) 2020.02.07
기본문법  (0) 2020.02.06
DJango (Windows)  (0) 2020.01.31

IOT (Indexed Organized Table)

Database 관리/Oracle
반응형
  IOT Table
행구분 PK. ROWID 가 없다. ROWID
FULL SCAN 시 리턴 순서 PK 순에 따라 출력 없다.
Unique Constraint 불가  
Cluster 불가  
저장공간 Table 보다 감소  
Primary Key 필수  
Secondary Index PK + UROWID ( Universal Rowid based pk )  
장점 Auto Ordering  
반응형

'Database 관리 > Oracle' 카테고리의 다른 글

sql to csv  (0) 2020.04.07
SQL Developer 설치  (0) 2020.02.27
NESTED TABLE Column  (0) 2020.02.11
Oracle.Client.SQLPlus.1x.Ubuntu21 설치 ( window, linux 방식 동일 )  (0) 2020.01.17

NESTED TABLE Column

Database 관리/Oracle
반응형

참조) https://m.blog.naver.com/geartec82/220954927715

 

테이블 안에 특정 컬럼 값이 테이블 구조처럼 관리하고 사용되어 지는 방식을 말한다.
자동적으로 group by 형태로 저장하는 방식중에 하나이다.
 

 CREATE OR REPLACE TYPE my_tab_t AS TABLE OF VARCHAR2(30);
/
CREATE TABLE nested_table (id NUMBER, col1 my_tab_t)
       NESTED TABLE col1 STORE AS col1_tab;
      
SQL> desc nested_table
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 ID                                                 NUMBER
 COL1                                               MY_TAB_T

Insert data into table:

INSERT INTO nested_table VALUES (1, my_tab_t('A'));
INSERT INTO nested_table VALUES (2, my_tab_t('B', 'C'));
INSERT INTO nested_table VALUES (3, my_tab_t('D', 'E', 'F'));
COMMIT;

 



Select from nested table:
 

 SQL> SELECT * FROM nested_table;
        ID COL1
---------- ------------------------
         1 MY_TAB_T('A')
         2 MY_TAB_T('B', 'C')
         3 MY_TAB_T('D', 'E', 'F')

 



Unnesting the subtable:
 

 SQL> SELECT id, COLUMN_VALUE FROM nested_table t1, TABLE(t1.col1) t2;
        ID COLUMN_VALUE
---------- ------------------------
         1 A
         2 B
         2 C
         3 D
         3 E
         3 F
6 rows selected.

 



실예제>

nested table column을 통하여 한명의 고객이 주소값으로 여러개의 컬럼 값을 가질수 있게 관리합니다.
 

 CREATE TYPE address_t AS OBJECT (
   street  VARCHAR2(30),
   city    VARCHAR2(20),
   state   CHAR(2),
   zip     CHAR(5) );
/

CREATE TYPE address_tab IS TABLE OF address_t;
/

CREATE TABLE customers (
   custid  NUMBER,
   address address_tab )
NESTED TABLE address STORE AS customer_addresses;


INSERT INTO customers VALUES (1,
            address_tab(
              address_t('101 First', 'Redwood Shores', 'CA', '94065'),
              address_t('123 Maple', 'Mill Valley',    'CA', '90952')
            )                );

 



데이터 확인
 

 SQL> select c.custid, u.*
  2  from customers c, table (c.address) u
  3  ;

    CUSTID STREET                         CITY                 ST ZIP
---------- ------------------------------ -------------------- -- -----
         1 101 First                      Redwood Shores       CA 94065
         1 123 Maple                      Mill Valley          CA 90952

 


뷰에서 확인하는 방법

NESTED TABLE column 을 생성하면 USER_NESTED_TABLES and USER_NESTED_TABLE_COLS 두개의 뷰에서 확인할 수 있습니다.

뷰에서 NESTED TABLE,NESTED TABLE column 확인하는 방법
 

 SQL> select TABLE_NAME from USER_NESTED_TABLES;

TABLE_NAME
------------------------------
COL1_TAB

SQL> select TABLE_NAME,COLUMN_NAME from USER_NESTED_TABLE_COLS;

TABLE_NAME                     COLUMN_NAME
------------------------------ ------------------------------
COL1_TAB                       NESTED_TABLE_ID
COL1_TAB                       COLUMN_VALUE

반응형

'Database 관리 > Oracle' 카테고리의 다른 글

sql to csv  (0) 2020.04.07
SQL Developer 설치  (0) 2020.02.27
IOT (Indexed Organized Table)  (0) 2020.02.11
Oracle.Client.SQLPlus.1x.Ubuntu21 설치 ( window, linux 방식 동일 )  (0) 2020.01.17

Javascript.Hoisting

IT 용어, 인터넷 활용 등등
반응형

"var 변수;" 와 "function 함수명" 으로 선언된 경우, 최상위에 미리 자동 선언된다.

고로, 함수내부에서 어디서든 불러 사용할 수 있다.

 

"let 변수" 와 "함수명 = function" 은 할당 혹은 정의 이전에 사용할 수 없다.

 

참조) https://gmlwjd9405.github.io/2019/04/22/javascript-hoisting.html

반응형

'IT 용어, 인터넷 활용 등등' 카테고리의 다른 글

CI, DI  (0) 2020.04.20
ab (apache bench) 테스트  (0) 2020.03.26
whois.com 에서 whois.co.kr 로 이전하기  (0) 2019.07.01
Serverless Architecture  (0) 2018.12.06
Manage, Unmanaged, Native, JIT  (0) 2018.12.02

Django Rest FrameWork

Python, 파이썬
반응형

# 참조 ) https://ssungkang.tistory.com/entry/Django-django-rest-framework-%EB%A5%BC-%EC%9C%84%ED%95%9C-JSON-%EA%B8%B0%EC%B4%88?category=366160

 

   
JSON 처리 import json

myData = {
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": True,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    }
  ]
}

print(type(myData)) # <class 'dict'>

myDataJson = json.dumps(myData)
print(type(myDataJson)) # <class 'str'>

myDataReturn = json.loads(myDataJson)
print(type(myDataReturn)) # <class 'dict'>
ModelSerializer 를 통한 JSON 직렬화 설명 1) ModelSerializer 를 통해  JSONRenderer 에서 변환가능한 형태로 먼저 데이터를 변환
참조1) JSON 을 생성하는 Serializer 는 html 을 생성하는 Django.Form 과 유사
참조2) Serializer 는 Django.Form 과 유사, ModelSerializer = DJango.ModelForm 과 유사


ModelSerializer 를 통한 JSON 직렬화 예제 참조) https://ssungkang.tistory.com/entry/Django-django-rest-framework-%EB%A5%BC-%EC%9C%84%ED%95%9C-JSON-%EC%A7%81%EB%A0%AC%ED%99%94?category=320582



models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)







serializers.py
from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'







# config/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('core/', include('core.urls'), name='core'),
]






# core/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views

router = DefaultRouter()
router.register(r'posts', views.PostViewSet)

urlpatterns = [
    path('', include(router.urls)),
]







views.py
from django.shortcuts import render
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer






serializer = PostSerializer(post)
serializer.data

# {'id': 2, 'title': '제목 내용', 'message': '메세지 내용', 'created_at': '2019-11-18T18:52:57.489893Z', 'update_at': '2019-11-18T19:22:53.717588Z'}
type(serializer.data) 
# <class 'rest_framework.utils.serializer_helpers.ReturnDict'




serializer = PostSerializer(Post.objects.all())
serializer.data
# 오류

serializer = PostSerializer(Post.objects.all(), many=True)
serializer.data
# [OrderedDict([('id', 2), ('title', '제목 내용'), ('message', '메세지 내용'), ('created_at', '2019-11-18T18:52:57.489893Z'), ('update_at', '2019-11-18T19:22:53.717588Z')]), OrderedDict([('id', 3), ('title', '임시제목'), ('message', 'ㅡㅏㅏ'), ('created_at', '2019-11-18T18:52:57.489893Z'), ('update_at', '2019-11-18T18:52:57.499208Z')])]
type(serializer.data) 
<class 'rest_framework.utils.serializer_helpers.ReturnList'>





뷰에서의 JSON 응답 )
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.query import QuerySet

# QuerySet 타입에 대해서는 tuple로 변환
# Post 타입에 대해서는 dict로 변환
# 그 외에는 DjangoJSONEncoder 로 변환
class MyJSONEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, QuerySet):
            return tuple(obj)
        elif isinstance(obj, Post):
            return {'id':obj.id, 'title': obj.title, 'message': obj.message }
        return super().default(obj)




# View 에서 json 리턴
from django.http import JsonResponse

data = Post.objects.all() # 직렬화할 QuerySet
encoder = MyJSONEncoder # DjangoJSONEncoder를 커스튬한 Encoder
safe = False # default = True 로서 변환할 데이터의 타입이 dict인지 확인합니다. dict 가 아닐 경우에는 False로 설정해주어야 합니다. QuerySet 은 dict 타입이 아니므로 False로 설정합니다.
json_dumps_params = {'ensure_ascii':False} # 한글 등의 유니코드는 16진수로 표현되므로 이를 False 로 바꿔주면 한글문자가 그대로 출력됩니다.
kwargs = {}

response = JsonResponse(data, encoder, safe, json_dumps_params, **kwargs)

response

response.content.decode('utf8')
# [{"id": 2, "title": "제목 내용", "message": "메세지 내용"}, {"id": 3, "title": "임시제목", "message": "ㅡㅏㅏ"}]

 

반응형

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

DJango 의 장점  (0) 2020.02.12
DJango.ORM  (0) 2020.02.12
기본문법  (0) 2020.02.06
DJango (Windows)  (0) 2020.01.31
설치.DJango + Redis + Celery  (0) 2020.01.29

기본문법

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