본문 바로가기

프로그래밍 언어/python

self의 의미 정의 self는 클래스의 인스턴스를 나타낸다. 파이썬이 self를 사용하는 이유는 'Python은 메소드로 하여금 메소드가 속한 인스턴스는 자동으로 전달하지만, 자동으로 수신하지는 않는 방식(?)을 취했기 때문이다' 메소드의 첫번째 매개변수는 메소드를 호출하는 인스턴스이다 (이를 자동으로 전달한다고 표현하는가 보다) #it is clearly seen that self and obj is referring to the same object class check: def __init__(self): print("Address of self = ",id(self)) obj = check() print("Address of class object = ",id(obj)) Address of self = 1401.. 더보기
Python에서 Call By Reference 구현하는 법 핫한(?) GPT 에게 물어 보았다. --> 가변 객체를 함수 인자로 넘기라고 한다. 기본 지식으로... 파이썬은 Passed by Assignment 라고 한다. 즉, 어떤 값을 넘기느냐에 따라 Call By Value 혹은 Call By Reference로 동작할 수 있다고 한다. int, float와 같은 불가변(immutable)인자를 함수로 넘기면 call-by-value가 되고, list, tuple, dict과 같은 가변(mutable) 인자를 함수로 넘기로 넘기면 call-by-reference 로 동작한다. (정확하게 말하면, 파이썬은 모든 것이 객체 이기 때문에 가변 객체는 함수 안에서 새로운 값을 생성하지 않고, 불가변 객체는 새로운 값을 생성하기 때문에 각각 Call-by-refer.. 더보기
파이썬 프로퍼티(Property) 파이썬 속성 값을 숨기기 위해서 사용하는 setter, getter를 파이썬 프로퍼티를 이용하여 간단하게 구현할 수 있다 결론부터 말하자면, getter에는 @property를 붙이고, setter에는 @{속성이름}.setter 를 붙인다. @{속성이름}.deleter를 사용하여 속성을 제거하는데 사용할 수도 있다. class Person: def __init__(self): self.__age = 0 def get_age(self): # getter return self.__age def set_age(self, value): # setter self.__age = value james = Person() james.set_age(20) print(james.get_age()) class Person:.. 더보기
Data Classes 1. 설명 - 파이썬 3.7 부터 도입된 문법이고, 간략화된 데이터 정의를 가능하게 한다. class RegularCard: def __init__(self, rank, suit): self.rank = rank self.suit = suit def __repr__(self): return (f'{self.__class__.__name__}' \ f'(rank={self.rank!r}, suit={self.suit!r})' def __eq__(self, other): if other.__class__ is not self.__class__: return NotImplemented return (self.rank, self.suit) == (other.rank, other.suit) >>> queen_of.. 더보기
[OS] python 과 실행파일 1. 파이썬으로 외부 exe 파일 실행하기 import subprocess subprocess.call(["C:\\temp\\calc.exe"]) or import os os.system('"C:/Windows/System32/notepad.exe"') - 서브쉘에서 명령(문자열) 수행. 표준 C함수 system() 호출하여 구현. - command가 출력을 생성하면, 인터프리터 표준 출력 스트림으로 전송된다. ※ os.system 리턴 값 (SO 링크)(링크2) 2. 파이썬 프로그램을 exe 파일로 만들기 - pyinstaller를 통해 하나의 exe 파일을 생성할 수 있다. - 장점 : 하나의 exe 파일로 배포 가능. 압축이 되어 exe 파일 사이즈가 작다 - 단점 : 압축된 형태의 exe 파일이 .. 더보기
경로 유틸리티 os.path.abspath(path) - 파일의 절대 경로를 반환한다. os.path.abspath('tmp') >>> 'C:\\Python30\\tmp' ※ os.path.abspath(path) = os.path.dirname(path) + os.path.basename(path) os.path.isdir(path) - 입력 받은 경로가 디렉토리 라면 1을 반환 os.path.exists(checkpoint_dir) - 해당 디렉토리 path가 있는지 확인한다. 예시) 폴더가 존재하지 않을 경우 생성한다. if not os.path.exist(checkpoint_dir): os.makedirs(checkpoint_dit) os.path.basename(path) - 입력받은 경로의 기본 이름(bas.. 더보기
Collections utils ▶ Counter - 해시 가능한 객체를 카운팅 하기 위한 dict의 하위 클래스이다. - 리스트를 입력 값으로 넣으면 원소를 Key 값으로, 갯수를 Value 값으로 반환해 준다. import collections class collections.Counter([iterable-or-mapping]) 사용 예시 from collections import Counter myList = ['red', 'blue', 'red', 'green', 'blue', 'blue'] cnt = Counter(myList) print(cnt) ''' Counter({'blue': 3, 'red': 2, 'green': 1}) ''' for item, count in Counter(myList).items(): # cnt.. 더보기
Miscellaneous 1) python -m 의 의미 e.g. python -m canmatrix.cli.convert [args] -m 뒤에는 모듈 이름이 온다. -m은 sys.path에서 모듈을 검색하고 모듈을 실행한다. (파일 canmatrix.cli.convert.py 의 __main__ 모듈을 실행 한다) 즉, 인터프리터로 하여금 canmatrix.cli.convert를 모듈 취급하게 한다. 해당 옵션은 빌트인 모듈이나, C로 작성된 확장 모듈 파이썬 모듈 파일을 가지고 있지 않기 때문에 사용할 수 없다. 2) for-else문 - 파이썬에는 for-else문이 있다. - for문을 모두 완수(?) 하고 통과할 경우 else: 구문이 실행된다. - break 등으로 for문이 완료 되지 않았다면 실행되지 않는다. f.. 더보기