DBILITY

python class 본문

python

python class

DBILITY 2021. 8. 19. 15:29
반응형

내부 메써드 작성할 때 argument로 self는 기본인가?

__init__는 생성자, __del__은 소멸자겠지(?)

#######################################################################################
class Avenger:
    def __init__(self, name="", role="", tribe=""):  # initializer, constructor?
        self.name = name
        self.role = role
        self.tribe = tribe
        print(f'{self} initialization')

    def __del__(self):
        print(f'{self} Destructor called, {self} deleted.')

    def to_string(self):  # method
        print(self.name, self.role, self.tribe)


########################################################################################

iron_man = Avenger()
iron_man.name = 'Robert John Downey Jr.'
iron_man.role = 'Tony Stark(Iron man)'
iron_man.tribe = 'Human(Insane or Genius)'

black_widow = Avenger('Scarlett Ingrid Johansson', 'Natasha Romanoff(Black Widow)', 'Human(Cold or Weak)')

print(iron_man.name, iron_man.role, iron_man.tribe)

print(black_widow.name, black_widow.role, black_widow.tribe)

iron_man.to_string()

black_widow.to_string()

del iron_man
del black_widow

print(iron_man)

실행결과 중 하단의 오류는 소멸자 호출 후에 객체를 출력해 봄.

<__main__.Avenger object at 0x00000221A9653FD0> initialization
<__main__.Avenger object at 0x00000221A9653F70> initialization
Robert John Downey Jr. Tony Stark(Iron man) Human(Insane or Genius)
Scarlett Ingrid Johansson Natasha Romanoff(Black Widow) Human(Cold or Weak)
Robert John Downey Jr. Tony Stark(Iron man) Human(Insane or Genius)
Scarlett Ingrid Johansson Natasha Romanoff(Black Widow) Human(Cold or Weak)
<__main__.Avenger object at 0x00000221A9653FD0> Destructor called, <__main__.Avenger object at 0x00000221A9653FD0> deleted.
<__main__.Avenger object at 0x00000221A9653F70> Destructor called, <__main__.Avenger object at 0x00000221A9653F70> deleted.
Traceback (most recent call last):
  File "C:\Dev64\workspace\python_study\classandobject.py", line 36, in <module>
    print(iron_man)
NameError: name 'iron_man' is not defined

Process finished with exit code 1
반응형
Comments