Python

[Python]class, object

sagesse2021 2021. 11. 15. 18:02
반응형

class: 함수+변수 모아 놓은거

object : 클래스를 써서 만든거 (=instance)

class Person:  # person 클래스 생성
  def say_hello(self): # say_hello함수에 인자 self를 넣음
    print("안녕!")

p = Person()   # p 오브젝트 생성
p.say_hello()

//안녕 !

class Person:  
  name = "워니"    

  def say_hello(self):
    print("안녕! 나는" + self.name) #만들어진 object에서 변수를 활용해야될때 self인자 사용

p = Person()   
p.say_hello()

//안녕! 나는 워니

class Person:  
  def __init__(self, name): 
    self.name = name   # person에서 새로 쓸 변수들을 설정할 수 있다

  def say_hello(self):
    print("안녕! 나는 " + self.name) 

# 이름을 여러명 만들고 싶을때                                  
wonie = Person("워니")   # wonie라는 person()을 만들때 첫번째 인자로 name이 들어감
michael = Person("마이클")
jenny =  Person("제니")

wonie.say_hello()
michael.say_hello()
jenny.say_hello()

//안녕! 나는 워니

//안녕! 나는 마이클

//안녕! 나는 제니

  • name변수를 person( )이라는 오브젝트를 만들때 바로 할당하고싶을떄, 즉 name변수를 "워니"로 고정시키지 않고 오브젝트를 만들때 새로 이름을 짓고 싶을때 init 함수를 사용
  • init함수는 initilaize(초기화)를 줄여서 init

 

class Person:  
  def __init__(self, name): 
    self.name = name   # name변수 안에 값을 넣어라

  def say_hello(self, to_name):   # to_name인자를 받음 
    print("안녕! " + to_name + " 나는 " + self.name) 

                                
wonie = Person("워니")   
michael = Person("마이클")
jenny =  Person("제니")

wonie.say_hello("철수")  # to_name에 넣어줄 값을 넣음 
michael.say_hello("영희")
jenny.say_hello("미지")​

//안녕! 철수 나는 워니

//안녕! 영희 나는 마이클

//안녕! 미지 나는 제니

class Person:  
  def __init__(self, name, age):  # age인자 생성
    self.name = name
    self.age = age   # age변수에 나이를 넣음

  def say_hello(self, to_name):   
    print("안녕! " + to_name + " 나는 " + self.name)

  def introduce(self):     #introduce 함수 생성, self인자로 나이를 받음
    print("내 이름은 " + self.name +" 그리고 나는 " + str(self.age) +" 살이야") 

                                
wonie = Person("워니", 20)  # person()에 나이를 추가 
wonie.introduce()

//내 이름은 워니 그리고 나는 20 살이야

반응형

'Python' 카테고리의 다른 글

[Python]패키지 & 모듈  (0) 2021.11.16
[Python]상속(inheritance)  (0) 2021.11.16
[Python]과일 숫자 세는 프로그램 만들기(list, 조건문 사용)  (0) 2021.11.15
[Python]Dictionary  (0) 2021.11.15
[Python]Tuple  (0) 2021.11.14