μƒˆμ†Œμ‹

Languages/Python

[Python] 클래슀 예제 μ½”λ“œ

  • -
λ°˜μ‘ν˜•

lucete1230-cyberpolice.tistory.com/229?category=876734

μ €λ²ˆκΈ€μ—μ„œ 클래슀의 κ°œλ…μ„ 읡히고 μ•„λž˜ 예제λ₯Ό μ‹€μŠ΅ν•΄λ³΄μ„Έμš”~

* 제 곡뢀 λͺ©μ μš©λ„λ‘œ μ‹€μŠ΅ ν•œ 것이라 λ‚΄μš©μ΄ 쑰금 λΆ€μ‘± ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

 


 

#예제 1
class Student:
    def start(self):
        print('μ•ˆλ…•ν•˜μ„Έμš”')
    def printName(self,name):
        print('이름은 {0} μž…λ‹ˆλ‹€'.format(name))

stu = Student()
Student.start(stu)
stu.printName('홍길동')
#예제 2
class Student:
    schoolName = 'Korea'

stu1 = Student() # 객체 생성
stu2 = Student()

#id () : 객체의 μ£Όμ†Œλ₯Ό λŒλ €μ£ΌλŠ” λ‚΄μž₯ν•¨μˆ˜
print('stu1의 μ£Όμ†Œ : {0}'.format(id(stu1)))
print('stu2의 μ£Όμ†Œ : {0}'.format(id(stu2)))

#μœ„μ˜ 2개의 κ°μ²΄λŠ” 각각 μƒμ„±μžλ₯Ό ν˜ΈμΆœν•΄μ„œ λ§Œλ“€μ–΄μ§„ κ²ƒμ΄λ―€λ‘œ μ„œλ‘œ λ‹€λ₯Έ μ˜μ—­ μ°¨μ§€ν•˜κ³  λ§Œλ“¬

Student.schoolName='Seoul'

print("\nStudent의 학ꡐ : ", Student.schoolName)
print("stu1의 학ꡐ : ", stu1.schoolName)
print("stu2의 학ꡐ : ", stu2.schoolName)

'''
schoolName은 λ©”μ†Œλ“œ μ™ΈλΆ€μ—μ„œ λ§Œλ“€μ–΄μ§„ κ²ƒμ΄λ―€λ‘œ 
classλ³€μˆ˜κ°€ 되고 클래슀 λ³€μˆ˜λŠ” 1개만 λ§Œλ“€μ–΄μ„œ
ν΄λž˜μŠ€μ™€ ν΄λž˜μŠ€λ‘œλΆ€ν„° λ§Œλ“€μ–΄μ§„ 객체 λͺ¨λ‘κ°€ κ³΅μœ ν•΄μ„œ μ‚¬μš©
λ”°λΌμ„œ μœ„μ˜ 3개의 좜λ ₯문은 λͺ¨λ‘ λ™μΌν•œ 값을 좜λ ₯
'''
#예제 3

class Student:
    schoolName ='Korea'

    def setName(self, name):
        self.name = name

    def getName(self):
        return self.name

stu1 = Student()
stu2 = Student()

stu1.setName('홍길동')
stu2.setName('μœ€λ™μ£Ό')
#ν˜ΈμΆœν•  땐 selfμ•ˆμ”€. λ©”μ†Œλ“œ μ•ˆμ—μ„œλ§Œ self μ¨μ„œ λ‹€λ₯Έκ³³μ—μ„œλ„ κ°€μ Έλ‹€ μ“Έ 수 있음.
print("stu1의 이름 : {0}".format(stu1.getName()))
print("stu2의 이름 : {0}".format(stu2.getName()))

 

 

#일반 ν•¨μˆ˜μ™€ 클래슀 차이

#일반 ν•¨μˆ˜ 방법
result1 = 0
result2 = 0

def add1(num):
    global result1
    result1 += num
    return result1

def add2(num):
    global result2
    result2 += num
    return result2

print(add1(3))
print(add1(4))

print(add2(3))
print(add2(7))


#μ•„λž˜λŠ” 클래슀둜 λ³€ν™˜ν•œκ±° 
class Calculator:
    def __init__(self):
        self.result = 0

    def add(self, num):
        self.result += num
        return self.result

cal1 = Calculator()
cal2 = Calculator()

print(cal1.add(3))
print(cal1.add(7))

print(cal2.add(3))
print(cal2.add(10))
#클래슀 생성 예제 : ball
class Ball:
    # 객제의 attributeλ₯Ό 지정
    size = 0
    color = ''
    direction = ''

    def bounce(self):#객체의 methodλ₯Ό 지정
        if self.direction == 'down' :
            self.direction == 'up'
        else :
            self.direction = 'down'

myBall = Ball()
yourBall = Ball()

myBall.color = 'red' #myball 객체의 color 멀버 λ³€μˆ˜κ°’ 지정
yourBall.color = 'blue' #yourball 객체의 color 멀버 λ³€μˆ˜κ°’ 지정

print(myBall.color, ' ', yourBall.color)

#객체 μ΄ˆκΈ°ν™” μ‹€μŠ΅
class Ball:

    def __init__(self, size, color, direction):
        self.size = size
        self.color = color
        self.direction = direction


    def bounce(self):
        if self.direction =='down':
            self.direction = 'up'
        else:
            self.direction = 'down'
        print("Bounce to",self.direction)

myBall = Ball('small', 'Red', 'down')#객체의 μ΄ˆκΈ°κ°’μ„ μž…λ ₯ν•˜μ—¬ 생성
yourBall = Ball('small', 'Red', 'up')

for i in range(0,3):#곡 νŠ•κΈ°κΈ°
    myBall.bounce()
    yourBall.bounce()

 

객체 정보 좜λ ₯

-> 객체의 μ •ν˜•ν™”λœ 정보λ₯Ό κ°œλ°œμžκ°€ μž…λ ₯ κ°€λŠ₯

-> __str__() λ©”μ†Œλ“œλ₯Ό μ‚¬μš©

#객체 정보 좜λ ₯ ~ 예제 (μ‹€μŠ΅ 4)
class Ball:
    def __init__(self, size, color, direction):
        self.size = size
        self.color = color
        self.direction = direction

    def __str__(self):
        msg = 'Hi, l\'m a ' + self.size + ' ' + self.color + ' ball.'
        return msg

myBall = Ball('small','Red','down') #객체의 μ΄ˆκΈ°κ°’ μž…λ ₯
print(myBall) #객체 정보값 좜λ ₯

 

μƒμ„±μžμ™€ μ†Œλ©Έμž

 

μ΄ˆκΈ°ν™” λ©”μ†Œλ“œ : __init__()

• 객체가 μƒμ„±λœ ν›„ κ°€μž₯ λ¨Όμ € 호좜되며 μžλ™μœΌλ‘œ ν˜ΈμΆœλ˜λŠ” λ©”μ†Œλ“œ

• “μ΄ˆκΈ°ν™”ν•˜λ‹€”λŠ” 뜻의 initializeλ₯Ό μ€„μ—¬μ„œ 뢙여진 이름

• 첫번째 λ§€κ°œλ³€μˆ˜λŠ” self 이며 이후에 λ§€κ°œλ³€μˆ˜ μΆ”κ°€ κ°€λŠ₯

• self μ΄μ™Έμ˜ λ§€κ°œλ³€μˆ˜κ°€ μžˆλŠ” μ΄ˆκΈ°ν™” λ©”μ†Œλ“œλ₯Ό λ§Œλ“€λ©΄ μΈμŠ€ν„΄μŠ€λ₯Ό 생성할 λ•Œ λ§€κ°œλ³€μˆ˜λ₯Ό λ„˜κ²¨μ£Όμ–΄μ•Ό ν•©λ‹ˆλ‹€.

• μΈμŠ€ν„΄μŠ€ λ³€μˆ˜λ₯Ό μ΄ˆκΈ°ν™” ν•˜κΈ° μœ„ν•œ λͺ©μ μœΌλ‘œ 주둜 μž‘μ„±

 

μ†Œλ©Έμž :__del__()

• 객체가 μ†Œλ©Έλ  λ•Œ μžλ™μœΌλ‘œ ν˜ΈμΆœλ˜λŠ” λ©”μ†Œλ“œ

• μ™ΈλΆ€ μžμ›μ„ μ‚¬μš©ν•˜λŠ” 경우 ν•΄μ œν•˜λŠ” μ½”λ“œλ₯Ό 주둜 μž‘μ„±

• self μ΄μ™Έμ˜ λ§€κ°œλ³€μˆ˜λ₯Ό 받지 μ•ŠμŠ΅λ‹ˆλ‹€.

 


 

μ•„λž˜λŠ” μƒμ„±μž μ†Œλ©Έμž 예제) 각 μ˜ˆμ œλ²ˆν˜ΈλŠ” λ‹€λ₯Έ μ˜ˆμ œμ΄λ‹ˆ λ”°λ‘œ μ‹€μŠ΅ν•΄λ³΄μ„Έμš”

#μƒμ„±μžμ™€ μ†Œλ©Έμž 예제
# μƒμ„±μž 예제 1
class Book:
    def __init__(self, bookName):
        self.name = bookName
        print("객체가 μƒμ„±λ˜μ—ˆμŠ΅λ‹ˆλ‹€. \nμ±…μ˜ 이름은 " + bookName + "μž…λ‹ˆλ‹€.")

objectBook = Book("λ‡Œλ₯Ό μžκ·Ήν•˜λŠ” 파이썬")

#μƒμ„±μž 예제2
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def aboutME(self):
        print("제 이름은 " + self.name + "이며, " + str(self.age)+"μ‚΄ μž…λ‹ˆλ‹€.")
adult = Person('홍길동',20)
adult.aboutME()

# μ†Œλ©Έμž 예제
class IceCream:
    def __init__(self, name, price):
        self.name = name
        self.price = price
        print(name+"의 가격은"+ str(price)+"원 μž…λ‹ˆλ‹€.")

    def __del__(self):
        print(self.name +"객체가 μ†Œλ©Έν•©λ‹ˆλ‹€.")

ice_cream = IceCream('λΆ€λΌλ³΄μ½˜',1000)
del ice_cream
ice_cream = IceCream('λΆ€λΌλ³΄μ½˜2',1000)

 


 

λ§ˆμ§€λ§‰ 총 정리 예제

#μƒμ„±μžμ™€ μ†Œλ©Έμž 예제 3
from time import ctime

class Student:
    #μƒμ„±μž
    def __init__(self, name = 'noname'):
        print('{0}에 객체가 μƒμ„±λ˜μ—ˆμŠ΅λ‹ˆλ‹€'.format(ctime()))
        self.name = name

    schoolNAme = 'korea'
    def setName(self, name):
        self.name = name
    def getName(self):
        return self.name

    #μ†Œλ©Έμž
    def __del__(self):
        print('{0}에 객체가 μ†Œλ©Έλ˜μ—ˆμŠ΅λ‹ˆλ‹€'.format(ctime()))

stu1 = Student("쀑앙")
stu2 = Student()
print("stu1의 이름 : {0}".format(stu1.getName()))
print("stu2의 이름 : {0}".format(stu2.getName()))
del stu1
del stu2

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

#ν΄λž˜μŠ€μ— λ©”μ†Œλ“œ μΆ”κ°€ν•˜κΈ° 1
class BusinessCard:
    def set_info(self, name, email, addr):
        self.name = name
        self.email = email
        self.addr = addr
member1 = BusinessCard()
print(member1)

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

# ν΄λž˜μŠ€μ— λ©”μ†Œλ“œ μΆ”κ°€ν•˜κΈ° 2
class BusinessCard:
    def set_info(self, name, email, addr):
        self.name = name
        self.email = email
        self.addr = addr

    def print_info(self):
        print("------------------")
        print("Name     :  ", self.name)
        print("Email     :  ", self.email)
        print("Address     :  ", self.addr)
        print("------------------")

member1 = BusinessCard()
member1.set_info("Yuna Kim","yunaKim@naver.com","Seoul")

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

#μƒμ„±μž - μžλ™ν˜ΈμΆœ, 객체 μ΄ˆκΈ°ν™”
#μΈμŠ€ν„΄μŠ€ 생성과 λ™μ‹œμ— μžλ™μœΌλ‘œ ν˜ΈμΆœλ˜λŠ” λ©”μ†Œλ“œ μ‚¬μš© : μƒμ„±μž
class BusinessCard:
    def __init__(self, name, email, addr):
        self.name = name
        self.email = email
        self.addr = addr

    def print_info(self):
        print("---------------------------------------")
        print("Name     :  ", self.name)
        print("Email    :  ", self.email)
        print("Address  :  ", self.addr)
        print("---------------------------------------")

member1 = BusinessCard("Yuna Kim","yunaKim@naver.com","Seoul")
member1.print_info()
λ°˜μ‘ν˜•
Contents

ν¬μŠ€νŒ… μ£Όμ†Œλ₯Ό λ³΅μ‚¬ν–ˆμŠ΅λ‹ˆλ‹€

이 글이 도움이 λ˜μ—ˆλ‹€λ©΄ 곡감 λΆ€νƒλ“œλ¦½λ‹ˆλ‹€.