๊ด€๋ฆฌ ๋ฉ”๋‰ด

IT’s Portfolio

[Python] ํด๋ž˜์Šค ๋‚ด์žฅ๋ชจ๋“ˆ ์ค‘ ์ž์ฃผ ์“ฐ์ด๋Š” __init__, __str__, __repr__์— ๋Œ€ํ•ด์„œ ๋ณธ๋ฌธ

Development Study/Python

[Python] ํด๋ž˜์Šค ๋‚ด์žฅ๋ชจ๋“ˆ ์ค‘ ์ž์ฃผ ์“ฐ์ด๋Š” __init__, __str__, __repr__์— ๋Œ€ํ•ด์„œ

f1r3_r41n 2020. 12. 5. 17:31
728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“Œ Class ๋‚ด์žฅ ๋ชจ๋“ˆ

 

 

 

__init__: initialize (์ดˆ๊ธฐํ™”)

class Test():
    def __init__(self, num1 = None, num2 = None):
        if num1 == None:
            self.num1 = "X"
        if num2 == None:
            self.num2 = "X"
            return
        self.num1 = num1
        self.num2 = num2

__init__ : ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค ๋•Œ ์ œ์ผ ์ฒ˜์Œ ์‹คํ–‰๋˜๋Š” ์ดˆ๊ธฐํ™” ๋ฉ”์„œ๋“œ์ด๋‹ค. ์ „๋‹ฌ๋ฐ›๋Š” ์ธ์ž๊ฐ€ self ์™ธ์— ๋‹ค๋ฅธ ๊ฒƒ์ด ์žˆ๋‹ค๋ฉด ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ์ธ์žฃ๊ฐ’์œผ๋กœ ๋„˜๊ฒจ์ฃผ๋ฉด __init__ ๋ฉ”์„œ๋“œ์—์„œ ์‚ฌ์šฉํ•œ๋‹ค.

__str__: string (๋ฌธ์ž์—ด)

    def __str__(self):
        if self.num1 == "X" or self.num2 == "X":
            return "์ „๋‹ฌ๋ฐ›์€ ์ธ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
        else:
            return f"print method : num1+num2={self.num1+self.num2}."

__str__ : ๊ฐ์ฒด ์ž์ฒด๋ฅผ ์ถœ๋ ฅํ•  ๋•Œ ๋„˜๊ฒจ์ฃผ๋Š” ํ˜•์‹์„ ์ง€์ •ํ•ด์ฃผ๋Š” ๋ฉ”์„œ๋“œ์ด๋‹ค.

__repr__: representation (ํ‘œํ˜„ํ•˜๋‹ค)

    def __repr__(self):
        if self.num1 == "X" or self.num2 == "X":
            return "์ „๋‹ฌ๋ฐ›์€ ์ธ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
        else:
            return f"interpreter : num1+num2={self.num1+self.num2}."

__repr__ : ์‚ฌ์šฉ์ž๊ฐ€ ๊ฐ์ฒด ์ž์ฒด๋ฅผ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ‘œํ˜„ํ•ด์ฃผ๋Š” ๋ฉ”์„œ๋“œ์ด๋‹ค.

 

๊ฒฐ๊ณผ

 

* ์ถ”๊ฐ€์‚ฌํ•ญ : __str__์ด ์„œ๋กœ ๋‹ค๋ฅธ ์ž๋ฃŒํ˜• ๊ฐ„ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์ œ๊ณตํ•˜๊ธฐ ์œ„ํ•œ ๋ชฉ์ ์œผ๋กœ ์กด์žฌํ•œ๋‹ค๋ฉด, __repr__๋Š” ํ•ด๋‹น ๊ฐ์ฒด๋ฅผ ์ธ๊ฐ„์ด ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ํ‘œํ˜„์œผ๋กœ ๋‚˜ํƒ€๋‚ด๊ธฐ ์œ„ํ•œ ์šฉ๋„์ด๋‹ค.

[์ถœ์ฒ˜] : duwjdtn11.tistory.com/241

 

__str__ ๊ณผ __repr__

0.__str__๊ณผ __repr__ 1. ๊ฐœ์š” ํŒŒ์ด์ฌ์—์„œ ๋งค์šฐ ์ž์ฃผ ์“ฐ์ด๊ณ  ์€๊ทผํžˆ ํ–‡๊ฐˆ๋ฆฐ๋Š ๋‘ ๋ฉ”์†Œ๋“œ์— ๋Œ€ํ•ด ๋‹ค๋ค„๋ณธ๋‹ค. __str_ ๊ณผ __repr__๋กœ์จ ์ด ๋‘˜์€ ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉ์ž๊ฐ€ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ž์—ด๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋‹ค. 2.

duwjdtn11.tistory.com

* ๋งŒ์•ฝ __str__์ด๋‚˜ __repr__ ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์ถœ๋ ฅํ•œ๋‹ค๋ฉด..

ํ•ด๋‹น ๊ฐ์ฒด์˜ ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ๊ฐ€ ์ถœ๋ ฅ๋˜๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

 

 

728x90
๋ฐ˜์‘ํ˜•
Comments