본문 바로가기
C++,python (인프런+사이트)/python 파이썬 정리

객체vs인스턴스vs클래쓰 & 인스턴스메서드vs클래스메서드vs스태틱메서드

by 알 수 없는 사용자 2022. 3. 31.

https://dojang.io/mod/page/view.php?id=2380 

 

파이썬 코딩 도장: 35.3 클래스 메서드 사용하기

이번에는 정적 메서드와 비슷하지만 약간의 차이점이 있는 클래스 메서드를 사용해보겠습니다. 클래스 메서드는 다음과 같이 메서드 위에 @classmethod를 붙입니다. 이때 클래스 메서드는 첫 번째

dojang.io

 

객체 vs인스턴스 vs 클래쓰  블로그

https://cerulean85.tistory.com/149

 

인스 클래스 스태틱 메서드 설명 블로그

https://journeytosth.tistory.com/73

 

참고

 


lion = Animal()   <- 객체 : lion , 클래쓰 : Animal() 

객체 vs인스턴스 vs 클래쓰 

결론 :  

객체(Object)는 소프트웨어 세계에 구현할 대상이고, 이를 구현하기 위한 설계도가 클래스(Class)이며, 이 설계도에 따라 소프트웨어 세계에 구현된 실체가 인스턴스(Instance)이다.  ( 객체 == 인스턴스 ) =! 클래쓰 

 

설명 : 

객체(Object)는 소프트웨어 세계에 구현할 대상이고, 이를 구현하기 위한 설계도가 클래스(Class)이며, 이 설계도에 따라 소프트웨어 세계에 구현된 실체가 인스턴스(Instance)이다.  

객체(Object)는 현실의 대상(Object)과 비슷하여, 상태나 행동 등을 가지지만, 소프트웨어 관점에서는 그저 콘셉(concept), 즉 사유의 결과일 뿐이다. 소프트웨어에서 객체를 구현하기 위해서는 콘셉 이상으로 많은 것들을 사고하여 구현해야 하므로, 이를 위한 설계도로 클래스를 작성한다. 설계도(class)를 바탕으로 객체(object)를 소프트웨어에 실체화 하면 그것이 인스턴스(Instance)가 되고, 이 과정을 인스턴스화(instantiation)라고 한다. 실체화된 인스턴스는 메모리에 할당된다.  

코딩을 할 때, 클래스 생성에 따라 메모리에 할당된 인스턴스를 ‘객체’라고 부르는데, 틀린 말이 아니다.  

인스턴스라고 부르면 더 정확하지만, 개념적으로 인스턴스는 객체에 포함된다고 볼 수 있다. 물론 어디가 소프트웨어 세계에 더 가깝냐를 따지면 당연히 인스턴스이다. 잘 구분해서 쓴다면 프로페셔널 하다는 소리를 들을 수 있을지도. 

그러나 객체나 인스턴스를 클래스로, 혹은 클래스를 객체나 인스턴스라고 해선 안 된다. 건물의 설계도를 보고 건물이라고 하지 않고, 반대로 건물을 설계도라고 하지 않으니까~ 


다른 블로그글에서의 클래스메서드 vs 인스턴스메서드 vs 정적메서드

 

  인스턴스 메서드  클래스 메서드  스태틱 메서드 
파라미터 차이  첫 번째 인자에 객체(인스턴스)를 의미하는 self 파라미터를 가짐  첫 번째 인자에 클래스를 의미하는 cls 파라미터를 가짐  첫 번쨰 인자를 따로 갖지 않는다. 
영향을 주는 곳  해당 인스턴스 메서드를 호출한 객체에만 영향을 미친다.  해당 클래스 메서드는 클래쓰에 영향을 준다.  해당 클래스 메서드는 클래스에 영향을 준다 
쓰는 목적 
 
객체(인스턴스)에 영향를 주기 위함  클래스에 영향을 주기 위함  객체(인스턴스), 클래스 모두 영향을 주지 않으면서,
def를 사용하고 싶을 때 주로 사용한다.
액세스 구간  객체(인스턴스)  클래스 내부  클래스 내부 
호출 방법  1. 클래스 안에선 self.메서드명 
2. 클래스 밖에선 객체.메서드명() 
1. 클래스 안에선 X 
2. 클래스 밖에선 클래스.메서드명() 
1. 클래스 안에선 X 
2. 클래스 밖에선 클래스.메서드명() 
       

ex) 1. 인스턴스메서드

class Test:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def print_info(self):
        print(self.name, ',', self.age) #1

    def test_func(self):
        self.print_info() 

test1 = Test('hong', 22)
test1.print_info() #2  결과값 : hong , 22 
test1.test_func() #3 결과값 : hong , 22

 

 

ex) 2. 클래스 메서드 ( "Person.count += 1" == "self.count += 1" )

class Person:
    count = 0 # 클래스 속성

    def __init__(self):
        Person.count += 1

    @classmethod
    def print_count(cls):
        print('{0}명 생성되었습니다.'.format(cls.count)) # 클래스 속성에는 엑세스가 가능하다.

    @classmethod
    def create(cls):
        p = cls() # 메서드 내부에서 cls()로 현재 클래스의 인스턴스를 만들 수도 있다. 즉, cls() = Person()을 의미한다.
        return p    

ryan = Person()
apeach = Person()

Person.print_count() # 결과값 : 2명 생성되었습니다.
print(Person.create()) # 결과값 : <__main__.Person object at 0x000001BA0AE143D0> Person클래스로 부터 생성된 인스턴스임을 확인할 수 있다.

 

ex) 3. 클래스 메서드 ( class 내의 변수를 변경하는 용도로 @class method를 쓰려면 free variable 구역에 선언 해줘야 한다. "school_name = 'ABC School'" 이렇게 )  ps> class method를 삭제 하기도 가능함

참조 사이트 : https://pynative.com/python-class-method/

 

class Student:
    school_name = 'ABC School'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def change_school(cls, school_name):
        cls.school_name = school_name

jessa = Student('Jessa', 20)
print(Student.change_school('XYZ School'))
print(Student.school_name)

# delete class method
del Student.change_school

# call class method
# it will give error
print(Student.change_school('PQR School'))

 

ex) 4. 스태틱 메서드

class Calc:

    count = 10 # 클래스 변수(클래스 속성)

    @staticmethod
    def add(a):
        print(a + Calc.count) # 클래스 속성에는 엑세스가 가능하다.

    @staticmethod
    def mul(a):
        print(a * Calc.count)

Calc.add(15) # 결과값 :25 
Calc.mul(15) # 결과값 : 150

ex) 5. 클래스 vs 스태틱 메서드

  • 예시 코드 : 클래스 메서드로 작성
class Figure:
    @classmethod
    def set_name(cls, name):
        cls.name = name

# Figure 클래스를 상속받음
class Circle(Figure):
    pass


Figure.set_name("figure")
print(Figure.name, Circle.name) # 결과값 : figure figure

Circle.set_name("circle")
print(Figure.name, Circle.name) # 결과값 : figure circle
  • 예시 코드 : 정적 메소드로 작성
class Figure:
    @staticmethod
    def set_name(name):
        Figure.name = name

# Figure 클래스를 상속받음
class Circle(Figure):
    pass


Figure.set_name("figure")
print(Figure.name, Circle.name) # 결과값 : figure figure

Circle.set_name("circle")
print(Figure.name, Circle.name) # 결과값 : circle circle

인프런에서 클래스메서드 vs 인스턴스 메서드 설명

1. 차이

클래스메소드        : 객체없이 사용 가능

인스턴스메소드     : 객체생성해서 사용 한다.  

 

2. 쓰는 이유

아래서 보면 알 수 있듯

인스턴스메소드는 말그대로 해당 인스턴스(변수)를 다루는 메소드고

클래스메소드도    말그대로 해당 (부모)클래스를 다루기 위한 메소드다

 

ex) car1 과 car2 각각의 가격을 가져오는 (해당인스턴스의) 가격을 가져오는 메소드 : Instance Method

     car1~9999를 에 해당하는 부모 Class의 전체 이자율을 다루는 메소드 : Class Method

 

class Car(object):   //안에 코드

 


 


# Chapter02-03
# 파이썬 심화
# 클래스 메소드, 인스턴스 메소드, 스테이틱 메소드

# 기본 인스턴스 메소드

# 클래스 선언
class Car(object):
    '''
    Car Class
    Author : Me
    Date : 2019.11.08
    Description : Class, Static, Instance Method
    '''

    # Class Variable
    price_per_raise = 1.0

    def __init__(self, company, details):
        self._company = company
        self._details = details
        
    def __str__(self):
        return 'str : {} - {}'.format(self._company, self._details)

    def __repr__(self):
        return 'repr : {} - {}'.format(self._company, self._details)

    # Instance Method
    # self : 객체의 고유한 속성 값 사용
    def detail_info(self):
        print('Current Id : {}'.format(id(self)))
        print('Car Detail Info : {} {}'.format(self._company, self._details.get('price')))
        
    # Instance Method
    def get_price(self):
        return 'Before Car Price -> company : {}, price : {}'.format(self._company, self._details.get('price'))

    # Instance Method
    def get_price_culc(self):
        return 'After Car Price -> company : {}, price : {}'.format(self._company, self._details.get('price') * Car.price_per_raise)

    # Class Method
    @classmethod
    def raise_price(cls, per):
        if per <= 1:
            print('Please Enter 1 or More')
            return
        cls.price_per_raise = per
        return 'Succeed! price increased.'

    # Static Method
    @staticmethod
    def is_bmw(inst):
        if inst._company == 'Bmw':
            return 'OK! This car is {}.'.format(inst._company)
        return 'Sorry. This car is not Bmw.'
    
    
# 자동차 인스턴스    
car1 = Car('Bmw', {'color' : 'Black', 'horsepower': 270, 'price': 5000})
car2 = Car('Audi', {'color' : 'Silver', 'horsepower': 300, 'price': 6000})

# 기본 정보
print(car1)
print(car2)
print()

# 전체 정보
car1.detail_info()
car2.detail_info()
print()

# 가격 정보(인상 전)
print(car1.get_price())
print(car2.get_price())
print()

# 가격 인상(클래스 메소드 미사용)
Car.price_per_raise = 1.2

# 가격 정보(인상 후)
print(car1.get_price_culc())
print(car2.get_price_culc())
print()

# 가격 인상(클래스 메소드 사용)
Car.raise_price(1.6)
print()

# 가격 정보(인상 후 : 클래스메소드)
print(car1.get_price_culc())
print(car2.get_price_culc())
print()

# Bmw 여부(스테이틱 메소드 미사용)
def is_bmw(inst):
    if inst._company == 'Bmw':
        return 'OK! This car is {}.'.format(inst._company)
    return 'Sorry. This car is not Bmw.'

# 별도의 메소드 작성 후 호출
print(is_bmw(car1))
print(is_bmw(car2))
print()

# Bmw 여부(스테이틱 메소드 사용)
print('Static : ', Car.is_bmw(car1))
print('Static : ', Car.is_bmw(car2))
print()

print('Static : ', car1.is_bmw(car1))
print('Static : ', car2.is_bmw(car2))

 

 

댓글