사용자 도구

사이트 도구


wiki:ai:python:클래스_상세_이해_self_클래스_인스턴스_변수

클래스 상세 이해(self, 클래스, 인스턴스 변수)

  • description : 클래스 상세 이해(self, 클래스, 인스턴스 변수)
  • author : 도봉산핵주먹
  • email : hylee@repia.com
  • lastupdate : 2020-06-25

클래스 상세 이해(self, 클래스, 인스턴스 변수)

예제 코드

# Section07-1
# 파이썬 클래스 상세 이해
# Self, 클래스, 인스턴스 변수
 
# 클래스, 인스턴스 차이 중요
# 네임스페이스 : 객체를 인스턴스화 할 때 저장된 공간
# 클래스 변수 : 직접 사용 가능, 객체보다 먼저 생성
# 인스턴스 변수 : 객체마다 별도로 존재, 인스턴스 생성 후 사용
 
# 예제1
 
print("#==== 예제 1 ====")
class UserInfo:
    def __init__(self, name):
        self.name = name
 
    def print_info(self):
        print("Name: " + self.name)
 
    def __del__(self):
        print("Instance removed!")
 
 
user1 = UserInfo("Kim")
user2 = UserInfo("Park")
 
print(id(user1))
print(id(user2))
 
user1.print_info()
user2.print_info()
 
print('user1 : ', user1.__dict__)  # 클래스 네임스페이스 확인
print('user2 : ', user2.__dict__)
 
print(user1.name)
 
print()
 
 
# 예제2
# self의 이해
 
print("#==== self의 이해 ====")
class SelfTest:
    def function1():
        print("function1 called!")
 
    def function2(self):
        print(id(self))
        print("function2 called!")
 
 
f = SelfTest()
# print(dir(f))
print(id(f))
# f.function1() #예외 발생 ->   function1() 에는 self가 없어서 class 변수입니다.
#                               class에서 직접 호출해야합니다.
#                호출 방식 ->   SelfTest.function1()
f.function2()
print(SelfTest.function1())
 
print()
 
# print(SelfTest.function2()) #예외 발생 ->   function2(self) 에는 self가 있어서 인스턴스 변수입니다.
#                                             인스턴스 선언해서 호출해야합니다.
#                                             호출 방식 ->   f.function2()
 
 
# 예제3
# 클래스 변수 , 인스턴스 변수
print("#==== 클래스 변수 , 인스턴스 변수 ====")
 
class Warehouse:
    # 클래스 변수
    stock_num = 0
 
    def __init__(self, name):
        # 인스턴스 변수
        self.name = name
        Warehouse.stock_num += 1
 
    def __del__(self):
        Warehouse.stock_num -= 1
 
 
user1 = Warehouse('Kim')
user2 = Warehouse('Park')
 
print(user1.name)
print(user2.name)
print(user1.__dict__)
print(user2.__dict__)
print(Warehouse.__dict__)  # 클래스 네임스페이스 , 클래스 변수 (공유)
 
# Warehouse.stock_num = 50 # 직접 접근 가능
 
print(user1.stock_num)
print(user2.stock_num)

실행 콘솔

#==== 예제 1 ====
2190468880608
2190468882096
Name: Kim
Name: Park
user1 :  {'name': 'Kim'}
user2 :  {'name': 'Park'}
Kim
 
#==== self의 이해 ====
2190468948368
2190468948368
function2 called!
function1 called!
None
 
#==== 클래스 변수 , 인스턴스 변수 ====
Instance removed!
Instance removed!
Kim
Park
{'name': 'Kim'}
{'name': 'Park'}
{'__module__': '__main__', 'stock_num': 2, '__init__': <function Warehouse.__init__ at 0x000001FE021F69D0>, '__del__': <function 
Warehouse.__del__ at 0x000001FE021F6A60>, '__dict__': <attribute '__dict__' of 'Warehouse' objects>, '__weakref__': <attribute '__weakref__' of 'Warehouse' objects>, '__doc__': None}
2
2

Tip

/var/services/web/dokuwiki/data/pages/wiki/ai/python/클래스_상세_이해_self_클래스_인스턴스_변수.txt · 마지막으로 수정됨: 2023/01/13 18:44 (바깥 편집)