YUYANE

Python / special method : __init__, __str__ 본문

Programming Languages/PYTHON

Python / special method : __init__, __str__

YUYA 2021. 1. 25. 16:25

학습 강의

www.udemy.com/course/python-and-django-full-stack-web-developer-bootcamp/

nomadcoders.co/python-for-beginners/lobby

 

 

Special method

class Car():
    wheels = 4
    doors = 4
    windows = 4
    seats = 4


print(dir(Car))

dir 함수를 출력해보면 파이썬에 이미 내장되어 있는 함수 목록들을 볼 수 있다. 오늘은 그 중에서 __init__과 __str__ 두 가지 함수를 살펴볼 것이다.

 

 

__init__

 

class Cat():

	def __init__(self,breed,name):
    	    self.breed = breed
            self.name = name
        

mycat = Cat("Korean Short Hair","Seol")
print(mycat.breed) # Korean Short Hair
print(mycat.name) # Seol

 

- 초기화 함수

- 객체를 만들 때 실행된다.

- 매개변수 self 는 필수로 들어가야 하며, class 객체를 가리킨다.

 

 

__str__

 

class Book():
    def __init__(self, title, author, pages):
        print "A book is created"
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):
        return "Title:%s , author:%s, pages:%s " %(self.title, self.author, self.pages)
        
        
b = Book("Python","Jose",200)
print(b) #Title: Python, Author: Jose, Pages: 200
        
        

- 문자열화 함수

- 클래스 객체를 string으로 출력할 때의 형식을 지정해주는 함수

 

 

 

참고

programmers.co.kr/learn/courses/2/lessons/326#note

Comments