Class
클래스는 객체(Object)를 만들기 위한 방법입니다. 클래스는 변수와 객체 그리고 관련된 기능들을 선언할 수 있습니다. 파이썬에서 클래스를 만들기 위해 'class' 키워드를 사용합니다.
Instance
객체(Object)는 클래스의 생성자를 사용하여 생성합니다. 이 객체를 클래스의 인스턴스라 부릅니다.
Python의 매소드 종류
Python에는 3가지의 매소드 타입이 존재합니다. static 매소드, class 매소드, instance 매소드. 3가지는 각각 다른 기능을 가지며 필요에 따라 사용해야 합니다.
1. Static 매소드
static 매소드는 생성할때 @staticmethod를 명시해줘야 합니다. static 매소드의 가장 중요한 특징은 인스턴스화 하지 않고 매소드를 호출 할 수 있습니다. static 메소드는 독립적으로 사용되기 때문에 다른 속성에 액세스하거나 해당 클래스 내의 다른 메소드를 호출 할 수 없습니다.
class가 있을때 static 매소드를 사용할 수 있고 매소드에 엑세스 하기 위해 특정 인스턴스가 필요하지 않습니다. 예를 들어 Math라는 클래스가 있고 factorial이라는 메서드가있는 경우 static 메소드를 사용할 수 있도록 해당 메소드를 호출하기 위해 특정 인스턴스가 필요하지 않을 수 있습니다.
[ static 매소드의 예제 ]
class Math:
@staticmethod
def factorial(number):
if number == 0:
return 1
else:
return number * MethodTypes.factorial(number - 1)
factorial = MethodTypes.factorial(5)
print(factorial)
2. class 매소드
class 매소드는 static 매소드와 동일한 방식으로 @classmethod를 명시해 줘야 합니다. class 매소드 또한 static 매소드와 마찬가지로 클래스를 인스턴스화 하지 않아도 호출이 가능합니다. 차이점은 다른 메소드 및 클래스 속성에 액세스 할 수있는 기능에 의존하지만 인스턴스 속성은 없습니다.
3. instance 매소드
instance 매소드는 클래스를 인스턴스화 했을때만 호출이 가능합니다. 해당 클래스의 객체가 생성되면 인스턴스 메소드를 호출하고 예약어 self를 통해 해당 클래스의 모든 속성에 액세스 할 수 있습니다. instance 메소드는 새 인스턴스 속성을 creating, getting 및 setting 하고 다른 인스턴스, 클래스 및 정적 메소드를 호출 할 수 있습니다.
class MethodTypes:
name = "Ragnar"
def instanceMethod(self):
# Creates an instance atribute through keyword self
self.lastname = "Lothbrock"
print(self.name)
print(self.lastname)
@classmethod
def classMethod(cls):
# Access a class atribute through keyword cls
cls.name = "Lagertha"
print(cls.name)
@staticmethod
def staticMethod():
print("This is a static method")
# Creates an instance of the class
m = MethodTypes()
# Calls instance method
m.instanceMethod()
MethodTypes.classMethod()
MethodTypes.staticMethod()
self와 cls의 차이점
self, cls의 키워드의 차이점은 오직 매소드 타입에 있습니다. instance 매소드를 사용하면 self 키워드를 사용하고 class 매소드를 사용하면 cls 키워드를 사용합니다. static 매소드는 속성에 접근할 수 없기 때문에 사용하는 키워드가 없습니다.
속성에 접근하기 위한 방법이며 매소드의 종류에 따라 self, cls 키워드를 사용한다고 생각하면 됩니다.
'Python 프로그래밍' 카테고리의 다른 글
[Python] Example of Magic Method (0) | 2022.05.13 |
---|---|
[Python] Magic Method (Special Method) (0) | 2022.05.11 |
[Python] Closer (0) | 2022.05.02 |
[Python] 일급 객체 (First-Class Citizen) (0) | 2022.04.30 |
[Python] enumerate 함수 (0) | 2022.04.28 |