[Python] Class 클래스 개념

2023. 1. 1. 19:40·Programming
반응형

클래스의 개념 

namespace : 객체마다 별도 존재

class 변수 : 직접 접근 가능, 공유

인스턴스 변수 : 객체마다 별도 존재 

class Dog:  # object 상속
    # 클래스 속성
    species = 'firstdog'

    # 초기화/인스턴스 속성
    def __init__(self, name, age):
        self.name = name
        self.age = age


# 클래스 정보
print(Dog)

>>> <class '__main__.Dog'>

# 인스턴스화
a = Dog("mikky", 2)
b = Dog("baby", 3)

# 비교
print(a == b, id(a), id(b))

>>> False 4560946848 4560946704

# 네임스페이스
print('dog1', a.__dict__)
print('dog2', b.__dict__)

>>> dog1 {'name': 'mikky', 'age': 2}
>>> dog2 {'name': 'baby', 'age': 3}

# 인스턴스 속성 확인
print('{} is {} and {} is {}'.format(a.name, a.age, b.name, b.age))

>>> mikky is 2 and baby is 3

if a.species == 'firstdog':
    print('{0} is a {1}'.format(a.name, a.species))

>>> mikky is a firstdog

print(Dog.species)
print(a.species)
print(b.species)

>>> firstdog
>>> firstdog
>>> firstdog

 

Self의 이해

self가 있으면 인스턴스 매소드 -> f.func2() or SelfTest.func2(f)로 호출

self가 없다면 클래스 매소드 -> SelfTest.func1()로 호출

class SelfTest:
    def func1():
        print('Func1 called')

    def func2(self):
        print(id(self))
        print('Func2 called')


f = SelfTest()

print(id(f))
>>> 4367323440

# f.func1() # 예외
f.func2()
SelfTest.func1()

# SelfTest.func2() # 예외
SelfTest.func2(f)

 

클래스 변수 & 인스턴스 변수 

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('Lee')
user2 = Warehouse('Cho')

print(Warehouse.stock_num)
>>> 2

# Warehouse.stock_num = 0.0094
print(user1.name)
print(user2.name)
print(user1.__dict__)
print(user2.__dict__)
print('before', Warehouse.__dict__)
print('>>>', user1.stock_num)

>>> Lee
>>> Cho
>>> {'name': 'Lee'}
>>> {'name': 'Cho'}
>>> before {'__module__': '__main__', 'stock_num': 2, '__init__': <function Warehouse.__init__ at 0x1080d9790>, '__del__': <function Warehouse.__del__ at 0x1080d98b0>, '__dict__': <attribute '__dict__' of 'Warehouse' objects>, '__weakref__': <attribute '__weakref__' of 'Warehouse' objects>, '__doc__': None}
>>> 2

del user1
print('after', Warehouse.__dict__)
>>> after {'__module__': '__main__', 'stock_num': 1, '__init__': <function Warehouse.__init__ at 0x1080d9790>, '__del__': <function Warehouse.__del__ at 0x1080d98b0>, '__dict__': <attribute '__dict__' of 'Warehouse' objects>, '__weakref__': <attribute '__weakref__' of 'Warehouse' objects>, '__doc__': None}

 

class Dog:  # object 상속
    # 클래스 속성
    species = 'firstdog'

    # 초기화/인스턴스 속성
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def info(self):
        return '{} is {} years old'.format(self.name, self.age)

    def speak(self, sound):
        return "{} says {}!".format(self.name, sound)


# 인스턴스 생성
c = Dog('july', 4)
d = Dog('Marry', 10)

# 메소드 호출
print(c.info())
print(d.info())

>>> july is 4 years old
>>> Marry is 10 years old

# 메소드 호출
print(c.speak('Wal Wal'))
print(d.speak('Mung Mung'))

>>> july says Wal Wal!
>>> Marry says Mung Mung!

 

 

해당 글은 인프런의 [프로그래밍 시작하기 : 파이썬 입문-Inflearn Original ] 강의를 듣고 정리한 개인적인 학습 노트 입니다.

반응형
'Programming' 카테고리의 다른 글
  • [Python] Package란 무엇인가?
  • [Python] module
  • [Python] 입력
  • [Python] 파이썬의 함수
기록하기-
기록하기-
  • 기록하기-
    꾸밈없이 끊임없이
    기록하기-
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Programming
      • Episode
  • 블로그 메뉴

    • 깃허브
    • 링크드인
  • 링크

    • Github
    • LinkedIn
  • 공지사항

  • 인기 글

  • 태그

    파이썬기초
    Python 문법
    python
    python class
    파이썬
    파이썬문법
    python 기초 문법
    Django
    파이썬 기초
    파이썬 문법
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
기록하기-
[Python] Class 클래스 개념
상단으로

티스토리툴바