Python

[Python] Class란? 개념잡기

Jeong Jeon
반응형

자 저번에 알아본 Class와 method에 이어 공부할 시간이다.

이번엔 __init__() 이라는 특이한 아이를 먼저 확인 해볼 건데, 이 아이는 Class의 생성자라고 생각하면 될것 같다

인스턴스 생성 시 바로 포함되어야 할 데이터는 생성자(init)로 정의해서 사용하며,

 

클래스명.메소드로 사용시 메모리에 필요한 데이터를 적재(instance생성 -> 적재) 후 해당 인스턴스를 self에 대입하여 호출하는 방식으로 사용 할 수 있다.

  • Company.inform()으로 실행했을경우 오류가 나는 이유
    • def inform(self) 메소드는 self(instance)를 가지고있어야 한다. 하지만 클래스명.메소드명으로 실행할 경우 인스턴스는 어디에도 적재되어있지 않다. 여기서 com1을 넣어주면 오류가 없어지는것을 볼수 있는데, com1은 instance를 메모리에 적재시켜놓은 아이기 때문에 해당 instance를 inform(self) 메소드가 참조를 할 수 있어지기 때문에 오류 없이 실행되는것을 알 수 있다.
>>> class Company :
...     def __init__(self,name,phone,pay):
...             self.name = name
...             self.phone = phone
...             self.pay = pay
...     def inform(self):
...             return '{}{}'.format(self.name,self.phone)
...
>>> com1 = Company('Bab','01099999999',50000)
>>> com2 = Company('R2','01088888888',90000)
>>>
>>> com1.inform()
'Bab01099999999'
>>> com2.inform()
'R201088888888'
>>> Company.inform()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: inform() missing 1 required positional argument: 'self'
>>> Company.inform(com1)
'Bab01099999999'

 

  • 클래스 메소드
class Human:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex

    def who(self):
        print("이름: {} 나이: {} 성별: {}".format(self.name, self.age, self.sex))

    def setInfo(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex


areum = Human("불명", "미상", "모름")
areum.who()      # Human.who(areum)

areum.setInfo("아름", 25, "여자")
areum.who()      # Human.who(areum)

 

  • 클래스 소멸자 메소드

신기하게 Python은 소멸자라는게 따로있다... 인스턴스를 삭제하면서 실행되는 메소드

>>> areum = Human("아름", 25, "여자")
>>> del areum
나의 죽음을 알리지 말라

 

  • 클래스 상속
#1번 예제
class 차:
    def __init__(self, 바퀴, 가격):
        self.바퀴 = 바퀴
        self.가격 = 가격


class 자전차(차):
    def __init__(self, 바퀴, 가격, 구동계):
        super().__init__(바퀴, 가격)
        #차.__init__(self, 바퀴, 가격)
        self.구동계 = 구동계


bicycle = 자전차(2, 100, "시마노")
print(bicycle.구동계)
print(bicycle.바퀴)

==>시마노
==>2

#2번 예제
class Car():
  def __init__(self,wheel,price):
      self.wheel = wheel
      self.price = price

class Zadongcha(car):
  def __init(self,wheel,price):
      super().__init__(wheel,price)
  def inform(self):
      print(self.wheel,self.price)
      
car = Zadongcha(1,2)
car.infor()
==> 1  2
반응형

'Python' 카테고리의 다른 글

[Python] Pandas 기초공부 -DataFrame  (0) 2021.01.13
[Python] Pandas 기초 공부 - Series  (0) 2021.01.13
[Python] Self 및 Class개념 잡기  (0) 2021.01.04
[Python] - JSON Parsing(파싱)  (0) 2020.12.30
[Python] Closure 및 Decorator  (0) 2020.12.29