본문 바로가기

컴퓨터

연산자 중복 정의 메서드로 동작 시키지 않고 연산자로 메서드를 동작 시킬 수 있다 >>> class GString:def __init__(self, init=None):self.content = initdef __sub__(self, str):for i in str:self.content = self.content.replace(i,'')return GString(self.content)def Remove(self, str):return self.__sub__(str) >> g = GString("ABCDEFGabcdefg")>>> g.Remove("Adg")>>> g.content'BCDEFGabcef'>>> g - "Bcf">>> g.content'CDEFGabe' __sub__는 연산자 중복을 위해 미리 정의된 특별.. 더보기
정적메서드, 클래스메서드 정적메서드 - 인스턴스 객체를 통하지 않고 클래스를 직접 호출할 수 있는 메서드클래스메서드 - 암묵적으로 첫 인자로 클래스 객체가 전달두 경우 모두 클래스 내에서 등록해야 함 = staticmethod(클래스 내에 정의한 메서드 이름) = classmethod(클래스 내에 정의한 메서드 이름) >>> class CounterManager:insCount = 0def __init__(self):CounterManager.insCount += 1def printInstaceCount():print("Instance Count: ", CounterManager.insCount)>>> a, b, c = CounterManager(), CounterManager(), CounterManager()>>> Count.. 더보기
생성자, 소멸자 메서드 생성자 메서드 __init__()소멸자 메서드 __del__()>>> class MyClass: def __init__(self, value): self.Value = value print("Class is created! Value = ", value) def __del__(self): print("Class is deleted!") >>> def foo(): d = MyClass(10) >>> foo() Class is created! Value = 10 Class is deleted! >>> class MyClass: def __init__(self, value): self.Value = value print("Class is created! Value = ", value) def __del__(s.. 더보기
클래스 객체와 인스턴스 객체의 관계 인스턴스 객체가 어떤 클래스로부터 생성됐는지 확인하는 방법isinstance(인스턴스 객체, 클래스 객체) >>> class Person: pass >>> class Bird: pass >>> class Student(Person): pass >>> p, s = Person(), Student() >>> print("p is instance of Person: ", isinstance(p, Person)) p is instance of Person: True >>> print("p is instance of Person: ", isinstance(s, Person)) > print("p is instance of Person: ", isinstance(p, object)) > print("p is ins.. 더보기
클래스 객체 와 인스턴스 객체의 이름공간 인스턴스 객체를 통해 변수나 함수의 이름을 찾는 순서인스턴스 객체 영역 >>> 클래스 객체 영역 >>> 전역 영역순서대로 해도 찾지 못하는 경우 AttributeError 예외가 발생 >>> class Person: name = "Default Name" >>> p1 = Person() >>> p2 = Person() >>> print("p1's name: ", p1.name) p1's name: Default Name >>> print("p2's name: :", p2.name) p2's name: : Default Name생성된 두 인스턴스 객체는 클래스의 데이터를 참조 p1, p2에는 아직 인스턴스 객체만의 특화된 데이터가 없기 때문에 클래스 객체의 데이터를 참조 >>> print("p1's nam.. 더보기
클래스 선언 데이터와 메서드가 없는 클래스>>> class MyClass: """Very simple class""" pass >>> dir() ['MyClass', '__builtins__', '__doc__', '__name__', '__package__'] >>> type(MyClass) 멤버 변수와 메서드가 있는 클래스>>> class Person: Name = "Default Name" def Print(self): print("My Name is {0}".format(self.Name)) >>> p1 = Person() >>> p1.Print() My Name is Default Name self - 현재 인스턴스 객체를 가리키는 것(this 키워드와 동일) 바운드 메서드 - 메서드를 호출할 때 암묵적으로.. 더보기
리눅스 실행 파일 리눅스에서는 확장자 구분 없이 실행 가능한 파일(바이너리 파일)과 비실행 파일로 구분 리눅스 파일들은 대소문자 구별을 확실히 함 1 파일 및 디렉토리 보기(ls)1 기능도스의 dir과 같은 기능을 가진 파일 목록 출력 명령어 2 사용법ls [옵션] 3 옵션-a, -all: 디렉토리내의 모든 파일 출력-l, -format=long: 파일 정보(파일 종류, 퍼미션, 사이즈)를 표시-s, -size: 1k 블록 단위로 파일 크기 표시-t, --sort=time: 최근의 파일부터 출력-c, --time: 파일 최근 변경 시간에 따라 정렬해서 출력--color: 파일 종류에 따라 색상 표시-R (recursive): 현재 작업 디렉토리와 하위 디렉토리 모두 출력--help 도움말 ls -a 도트(.)로 된 숨겨진.. 더보기
리눅스 시스템 끄기 shutdown 명령은 오직 시스템 관리자 계정인 루트만이 실행할 수 있음1 사용방법shutdown [경고 메시지] 2 옵션-t 시간(초): 다른 런레벨로 바뀌기 전 경고를 내보내는 프로세스와 kill 시그널 사이의 기다리는 시간-k: 실제적으로 셧다운하는 것이 아니라, 사용자 모두에게 경고 메세지만 전달하는 옵션-r: 셧다운 후 리부팅하기-h: 셧다운 후 시스템 정지-c: 실행중인 셧다운 취소-f: 빠른 부팅, 부팅 시 fsck를 점검하지 않도록 함 시간now: 지금 바로+m: 지정한 m분 이후에hh:mm: 몇 시 : 몇 분에 명령shutdown -r now: 시스템 리부팅shutdown -h now: 시스템 바로 종료shutdown -h +5 5분 후에 시스템이 종료됩니다.: 종료 메시지와 함께 5분.. 더보기
제어문과 연관된 유용한 함수 range() - 수열의 생성range(['시작값'], '종료값'[, '증가값'])'종료값'은 필수 항목'시작값'과 '증가값'은 선택적으로 입력기본적으로 '시작값'은 0, '증가값'은 1 >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(5, 10)) [5, 6, 7, 8, 9] >>> list(range(10, 0, -1)) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] >>> list(range(10,20,2)) [10, 12, 14, 16, 18] 리스트 항목과 인덱스 값을 동시에 얻는 법기존 방법>>> L = ['Apple', 'Orange', 'Banana'] >>> for i in range(len(L)): prin.. 더보기
break, continue, 그리고 else break>>> L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> for i in L:if i>5:breakprint("Item: {0}".format(i)) Item: 1Item: 2Item: 3Item: 4Item: 5 continue>>> for i in L:if i%2 == 0:continueprint("Item: {0}".format(i)) Item: 1Item: 3Item: 5Item: 7Item: 9 else블록이 수행되는 예제break으로 루프가 종료되지 않은 경우 else 수행L=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in L: if i%2 == 0: continue print("Item: {0}".format(i)) else: print(.. 더보기