๐Ÿ“Œ OOP With Python

Gyeomiiยท2022๋…„ 6์›” 21์ผ
0

DDITPython

๋ชฉ๋ก ๋ณด๊ธฐ
4/18
post-thumbnail

๐Ÿ“Œ OOP With Python

Animal ํด๋ž˜์Šค

class Animal:
    def __init__(self):
        self.age = 1
    
    def happyBirth(self):
        self.age += 1

Human ํด๋ž˜์Šค

class Human(Animal):
    def __init__(self):
        super().__init__() #๋ถ€๋ชจํด๋ž˜์Šค์˜ ์ƒ์„ฑ์ž ํ˜ธ์ถœ
        self.money = 10000
        
    def albamon(self):
        self.money += 1

๊ฐ์ฒด ์ƒ์„ฑ

a = Animal()
h = Human()

์ถœ๋ ฅ

# Human ๊ฐ์ฒด ์ƒ์„ฑ (Animal ์ƒ์†๋ฐ›์Œ)
h = Human()

print(f"๋‚˜์ด : {h.age}")
print(f"์ž์‚ฐ : {h.money}")
print("happyBirth, albamon ์‹คํ–‰")
h.albamon()
h.happyBirth()

print(f"๋‚˜์ด : {h.age}")
print(f"์ž์‚ฐ : {h.money}")

๊ฒฐ๊ณผ

๐Ÿ“Œ ๋‹ค์ค‘์ƒ์†์„ ๋ฐ›์„ ๋•Œ

๋ถ€๋ชจ ํด๋ž˜์Šค

class Xi:
    def __init__(self):
        self.money = 1000
    def steal(self, smoney):
        self.money += smoney

class Putin:
    def __init__(self):
        self.nuclear = 5000
    def alzheimer(self):
        self.nuclear -= 1

class JungEun:
    def __init__(self):
        self.missile = 10000
    def ssorau(self):
        self.missile -= 100

์ž์‹ํด๋ž˜์Šค

class Child(Xi, Putin, JungEun):
    def __init__(self):
        Xi.__init__(self)
        Putin.__init__(self)
        JungEun.__init__(self)
        
    def steal(self, smoney):
        super().steal(smoney)
        
    def alzheimer(self):
        super().alzheimer()
        
    def ssorau(self):
        super().ssorau()
  • ์—ฌ๋Ÿฌ ๋ถ€๋ชจํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›์„ ๋•Œ ๋ถ€๋ชจ์ƒ์„ฑ์ž์˜ ํ˜•ํƒœ๋ฅผ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์„ ์–ธํ•ด์ค€๋‹ค.
๋ถ€๋ชจ์ƒ์„ฑ์ž.__init__(self)
  • ๋ถ€๋ชจ์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ์ž์‹ํด๋ž˜์Šค์•ˆ์— ์„ ์–ธํ•ด์•ผํ•œ๋‹ค.

๊ฐ์ฒด ์ƒ์„ฑ

ch = Child()

์ถœ๋ ฅ

print(f"money : {ch.money}, nuclear : {ch.nuclear}, missile : {ch.missile}")
ch.steal(100)
ch.alzheimer()
ch.ssorau()
print(f"money : {ch.money}, nuclear : {ch.nuclear}, missile : {ch.missile}")

๊ฒฐ๊ณผ

๐Ÿ“Œ ๊ฐ์ฒด ์†Œ๋ฉธ

class Cat:
    def __init__(self):
        print("constructor")
        
    def crying(self):
        print("crying")    
    
    def __del__(self):
        print("destroyer")

		def __str__(self):
		        return "mew"

# ์ƒ์„ฑ์ž : __init__(self)
# ์†Œ๋ฉธ์ž : __del__(self)
# toString : __str__(self)
  • open์ด ๋˜์–ด์žˆ๋Š” ๊ฒƒ์€ ์ „๋ถ€ closeํ•ด์ค˜์•ผํ•œ๋‹ค.
  • ์ƒ์„ฑ์ž : open, ์†Œ๋ฉธ์ž : close

์‹คํ–‰์ฝ”๋“œ

c = Cat()
c.crying()
time.sleep(4)
print(c)

๊ฒฐ๊ณผ

profile
๊น€์„ฑ๊ฒธ

0๊ฐœ์˜ ๋Œ“๊ธ€