본문 바로가기

Python

[Python] 10. 클래스 정적 매소드 (classmethod / staticmethod)

#정리

** 정적 메소드는 두 가지 방법으로 함수 콜 가능 ( 정적 메소드 = classmethod, staticmethod )

 - 1. 일반 동적 함수 처럼 인스턴스 생성 후, 객체명으로 함수 콜
 - 2. 인스턴스를 만들지 않고 클래스명으로 직접 함수 콜

** @ : java에서는 anotaion, 파이썬에서는 decoration이라고 한다.

 

#27classmethod - 클래스 함수  

# classmethod는 cls(class)를 self 대신 활용한다.

 - @classmethod  #@ 데코레이션을 붙여서 함수를 생성한다.

 - def sleep(cls,time): #self >> cls(class)로 변경 필요
#정적 매소드의 두 가지 접근 방법
 - p.sleep(5) #객체명으로 접근
 - Person.sleep(12) #클래스명으로 접근

#cls의 활용

 - return cls() #자신을 불러와하여 새로운 인스턴스를 생성하는 것도 가능하다.
 - print("sleeptime:",Person.sleeptime)#cls로 클래스 변수값 접근 가능


#28staticmethod - 클래스 함수 

# staticmethod는 cls, self 모두 사용하지 않는다.

 - @staticmethod #@ 데코레이션을 붙여서 함수를 생성한다.

 - def sleep(aa): #self or cls 도 작성 안함.  

#정적 메소드로 객체명과 클래스명 둘 모두 접근가능

 - p.sleep("ss") #객체명으로 접근
 - Person.sleep("ss") #클래스명으로 접근

#return Person()을 통해 새로운 객체 생성

 - pp = Person.getPerson()


#29staticmethod /classmethod - 두 정적 함수의 차이

 #classmethod : 자식 클래스로 접근하면 자식 클래스의 속성으로 리턴된다.

 - pp1 = Student.sleep_class("aaa") 
 - print(pp1.userName) #cls() >> Student
#staticmethod : 자식 클래스로 접근해도 부모 클래스의 속성으로 리턴된다.
 - pp2 = Student.sleep_static("bbb")
 - print(pp2.userName) #Person() >> Person

 

 

 

 

 

** 정적 메소드는 두 가지 방법으로 함수 콜 가능 ( 정적 메소드 = classmethod, staticmethod )

 - 1. 일반 동적 함수 처럼 인스턴스 생성 후, 객체명으로 함수 콜
 - 2. 인스턴스를 만들지 않고 클래스명으로 직접 함수 콜

** @ : java에서는 anotaion, 파이썬에서는 decoration이라고 한다.

 

#27classmethod - 클래스 함수  

# classmethod는 cls(class)를 self 대신 활용한다.

 - @classmethod  #@ 데코레이션을 붙여서 함수를 생성한다.

 - def sleep(cls,time): #self >> cls(class)로 변경 필요
#정적 매소드의 두 가지 접근 방법
 - p.sleep(5) #객체명으로 접근
 - Person.sleep(12) #클래스명으로 접근

#cls의 활용

 - return cls() #자신을 불러와하여 새로운 인스턴스를 생성하는 것도 가능하다.
 - print("sleeptime:",Person.sleeptime)#cls로 클래스 변수값 접근 가능


--예문 코드 보기--

더보기
#!/usr/bin/env python
# -*- coding: utf-8 -*-

print("---------------")
#정적 메소드 = classmethod, staticmethod
#정적 메소드는 두 가지 방법으로 함수 콜 가능
#1. 일반 동적 함수 처럼 인스턴스 생성 후, 객체명으로 함수 콜
#2. 인스턴스를 만들지 않고 클래스명으로 직접 함수 콜
class Person:
	userName = "lee"
	sleeptime = 10
	def __init__(self):
		print("Person __init__")
		self.pname = "kim"
	
	@classmethod #파이썬에서는 decoration이라고 한다.
	def sleep(cls,time): #self >> cls(class)로 변경 필요
		print("def_sleep()...",time)
		cls.sleeptime = time
		
	@classmethod
	def getPerson(cls):
		print("getPerson()....")
		#return Person()
		return cls() #객체 생성
	
	
p = Person()
p.sleep(5) #객체명으로 접근
Person.sleep(12) #클래스명으로 접근

print("pname:",p.pname)
print("sleeptime:",Person.sleeptime)#cls로 클래스 변수값 접근 가능
print("---------------")
pp = Person.getPerson()
print(pp) #return cls() 로 인해 새로운 인스턴스 생성

 

 


#28staticmethod - 클래스 함수 

# staticmethod는 cls, self 모두 사용하지 않는다.

 - @staticmethod #@ 데코레이션을 붙여서 함수를 생성한다.

 - def sleep(aa): #self or cls 도 작성 안함.  

#정적 메소드로 객체명과 클래스명 둘 모두 접근가능

 - p.sleep("ss") #객체명으로 접근
 - Person.sleep("ss") #클래스명으로 접근

#return Person()을 통해 새로운 객체 생성

 - pp = Person.getPerson()

 

--예문 코드 보기--

더보기
#!/usr/bin/env python
# -*- coding: utf-8 -*-

print("---------------")
#정적 메소드로 객체명과 클래스명 둘 모두 접근가능

class Person:
	userName = "lee"
	def __init__(self):
		print("Person __init__")
		self.pname = "kim"
	
	@staticmethod
	def sleep(aa): #self or cls 도 작성 안함.  
		print("sleep()...",aa)
		Person.userName = aa

	@staticmethod
	def getPerson():
		print("getPerson()....")
		return Person() #새로운 객체 생성
		
p = Person()
print("userName:",p.userName)
print("pname:",p.pname)
p.sleep("ss") #객체명으로 접근
Person.sleep("ss") #클래스명으로 접근
p.pname = "park"

print("userName:",p.userName)
print("pname:",p.pname)
print("---------------")
pp = Person.getPerson()
print(pp) #return Person()을 통해 새로운 객체 생성

 

 


#29staticmethod /classmethod - 두 정적 함수의 차이

 #classmethod : 자식 클래스로 접근하면 자식 클래스의 속성으로 리턴된다.

 - pp1 = Student.sleep_class("aaa") 
 - print(pp1.userName) #cls() >> Student
#staticmethod : 자식 클래스로 접근해도 부모 클래스의 속성으로 리턴된다.
 - pp2 = Student.sleep_static("bbb")
 - print(pp2.userName) #Person() >> Person

 

--예문 코드 보기--

더보기
#!/usr/bin/env python
# -*- coding: utf-8 -*-

print("---------------")
#정적 메소드 = classmethod, staticmethod
#객체명과 클래스명 둘 모두 접근가능
class Person:
	userName = "super_name"
	def __init__(self):
		print("Person __init__")
		self.pname = "kim"
	
	#classmethod : 자식 클래스로 접근하면 자식 클래스의 속성으로 리턴된다.
	@classmethod
	def sleep_class(cls,time):
		print("sleep_class()...",time)
		cls.time = time
		return cls()	
	
	#staticmethod : 자식 클래스로 접근해도 부모 클래스의 속성으로 리턴된다.
	@staticmethod
	def sleep_static(pname): 
		print("sleep_static()...",pname)
		return Person()

print("--- super class access ---")
pp1 = Person.sleep_class("aaa") 
print(pp1.userName)

pp2 = Person.sleep_static("bbb")
print(pp2.userName)



print("--- sub class access ---")
class Student(Person):
	userName = "sub_name"
	
pp1 = Student.sleep_class("aaa") 
print(pp1.userName) #cls() >> Student

pp2 = Student.sleep_static("bbb")
print(pp2.userName) #Person() >> Person