머신러닝

Class, Object, POO (Object Oriented Programming), Inheritance

경희대생 2023. 2. 22. 15:09

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

python은 Objects 기반의 programming language이다. 여기서 objects란 크게 attributes와 behavior 두가지로 나뉜다.

 

attributes는 특성으로서 class 함수가 갖는 특성이고, behavior은 class 함수의 객체가 갖는 행동이다. 

 

class

In object-oriented programming, a class is an extensible program code template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods); (Wikipedia)

 

 

 

Class 만드는법

Class를 만드는 법은, class를 만들어준후 이후 instance (object생성)을 만들어주면 된다. 

 

 

attribute의 경우 __init__ (self, attribute1, attribute2, ..., attribute n ) 식으로 들어가며, 향후 object를 만들 때 넣어주는 object들의 특성이다. 

 

def __init__(self, attribute1, attribute2):

self.A = attribute1 

self.B = attribute2

 

가령 object 1 = class_name(attribute1, attribute2)로 object1을 만들어주면,

self.A -> attribute1 반환, self.B -> attribute2 반환한다. 

 

 

method의 경우, 특정 object (instance)을 만들었을 때, 그 object가 가질 수 있는 function이다. 

 

class class_name():

 

def __init__(self, attribute1, attribute2):

self.A = attribute1

self.B = attribute2

 

def method_name(self, method):

return method + 1 

 

object1 = class_name(self, attribute1, attribute2)

object1.A => attribute1 반환 

object1.B => attribute2 반환 

 

object1.method_name(method) => method + 1 반환

 

Class상속 (Inheritance) 

 

  • Inheritance is a way of creating a new class by using details of an existing class without modifying it. 
  • The newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class)
  • In the beside program, we created two classes
  • i.e. Bird (parent class), and Penguin (child class) 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Parent class는 Bird이고, parent class가 가지고 있는 attribute와 method를 child class인 Penguin이 상속받을 수 있다. 추가로 child class인 Penguin은 추가로 attribute 또는 method를 추가할 수 있다. 

 

class child_class(parent_class): 

 

def __init__(self):

super().__init__()

 

이런식으로 child_class에 parent_class를 상속받을 수 있다.