Python Objective-Oriented Programming Tutorial

Python Objective-Oriented Programming Tutorial

다뤄야 하는 함수가 늘다보니, 클래스로 관리해보고 싶단 생각이 들었다.

클래스에 관한 유튜브를 뒤지다가, 친절한 Python OOP 렉쳐 영상을 찾아서 올려본다.

Instance, Constructor, Attribute, Method, 등의 개념을 추상적으로 정의하고 넘어가는게 아니라 실제 사용례를 보여주며 알려준다.

(나같은) 객체지향 프로그래밍에 문외한들에게 추천.

Python OOP Tutorial 1: Classes and Instances

  • 학습내용: 

Constructor를 이용한 Class 선언, Instance 생성, Attribute과 Method의 사용. 

Python OOP Tutorial 2: Class Variables

-학습내용: Class variables (var in class) > Instance variables (self.var in class)”class.__dict__” vs “instance.__dict__” 로 비교 가능!Class와 Instance의 관계는 어쩌면, 플라톤의 이데아 비유에 견줄수도 있을듯..

Python OOP Tutorial 3: Class Methods and Static Methods

-학습내용: Regular method, Class method, Static method의 차이.Regular method는 instance를 첫번째 argument(self)로 써서 instance.method()의 형태로 호출할 수 있다.첫번째 argument를 Class로 쓰려면?Class method decorator “@classmethod”를 앞에 적어주고 나서 method를 선언해주면 된다.method 선언 방식은..@calssmethoddef method1(cls, arg1, arg2…): <- cls 는 class variable name!blah blah이 경우 regular method와 달리 class 자체, 혹은 class variable을 참조/변경할 수 있다!
영상 도중에 재밌는 경우를 알려주는데..constructor에서 요구하는 argument와 형태가 다른 입력으로도 class를 생성해주는 alternative constructor를 만들 수도 있다. 바로 class 자체를 호출할 수 있기 때문에,입력된 string을 쪼개고 난 결과를 constructor의 argument로 해서 instance를 만들어버릴 수도 있다.class안의 method가 class자체를 다시 호출하는, 강력하면서도 헷갈리기 쉬운 호출 형태라서 생각을 정리할 필요가 있다. 
Static method는 class variable이나 instance variable을 전혀 사용하지 않는 경우다.마찬가지로 “@staticmethod”라는 decorator를 앞에 써주고 선언하면 된다.

Python OOP Tutorial 4: Inheritance - Creating Subclasses

-학습내용: Inheritance와 Subclass. Inheritance(상속)은 이전에 작성해두었던 class의 모든 attribute, method를 가져오면서 새로운 클래스를 만드는 방식이다.선언 방식은 ..”class subclass(parent_class):” 라고 적으면 된다.즉, 클래스를 만들면서 다른 클래스를 argument로 넣으면, 그 클래스를 그대로 쓰게 된다. Constructor까지 가져오게 되니,instance 선언할 때도 똑같은 방식으로 만들면 된다.
상속을 여러번 해서 헷갈리다면… “print(help(subclass))” 라고 치면 parent_class에 대한 정보를 볼 수 있다.
constructor를 비롯한 method를 Override 하고 싶다면, 같은 이름의 method를 작성하면 그만이다.Tip1) subclass에서 parent_class를 참조하고 싶으면 “super().”(instance 호출)나 “parent_class”(class 호출)를 사용하면 된다.Tip2) parent_class의 constructor 도 부를 수 있다. “super().__init__(*args)” 나 “parent_class.__init__(self, *args)” 이렇게..Tip3) “isinstance(instance_name, class)” 함수: 인스턴스가 특정 클래스에 포함되는지 알려준다. 여기서 class 자리에 인스턴스를 생성할 때 쓴 클래스뿐 아니라, 그 클래스의 inheritance 관계에 있는 parent_class 까지 포함해서 True/False 를 알려준다. 

Python OOP Tutorial 5: Special (Magic/Dunder) Methods

-학습내용: Double underscore (Dunder)를 이용한 입력 변수에 따른 맞춤형 출력 method 만들기.
1) def __init__(self, arg1, arg2): ~ 2) def __repr__(self): ~ print(인스턴스) 실행하면 나오는 문장을 리턴함. 3) def __str__(self): ~ 마찬가지로 print(인스턴스) 실행하면 나오는 문장을 리턴함. 둘 다 있으면 str 보여줌.4) def __add__(self, other): ~ 인스턴스의 합을 정의할 수 있다.5) def __len__(self): ~ 인스턴스의 len() 함수를 정의할 수 있다. 요런 Dunder method들을 알아두면 standard library 볼 때 도움이 되겠지? 

Python OOP Tutorial 6: Property Decorators - Getters, Setters, and Deleters

-학습내용: 

Property Decorator ”@property”  :   method를 attribute처럼 쓸수있게 해 줌.”@method_name.setter”  :  @property로 선언한 method로 다른 attribute를 세팅해 줌.”@method_name.deleter” : “del method_name” 명령의 내용을 설정해 줌.

Share on: