class 클래스이름:
def __init__(self, inname): #객체 생성하면 바로 실행됨
self.name= inname #name은 속성
def 메서드이름(self,변수1,변수2):
실행할 코드
def 메서드이름(self,변수1,변수2):#self는 항상 들어감
실행할 코드
객체=클래스이름("철수") #객체(인스턴스) #객체가 self에 들어가게 됨
객체.메서드이름(매변1,매변2)
class monster:
def __init__(self,name,age):
self.name= name
self.age= age
def say(self):
print(f'나는{self.name} {self.age}살임')
shark=monster("상어",7)
shark.say()
>>> 나는 상어 7살임
__init__()을 생산자, shark 를 객체, 이때 shark는 self에 해당함, name은 속성
| 용어 | 뜻 |
|---|---|
| 클래스 | 붕어빵틀 |
| 객체 | |
| 속성 | 클래스 안의 변수(self.name에서 name) |
| 메서드 | 클래스 안의 함수 |
| 생산자 | |
| 인스턴스 | 객체 안에 인스턴스가 있음(벤다이어그램) |
str() 이 내장함수가 아니라 내장클래스!!!!라고 함
문자열을 반환하는 이 클래스의 기능을 이용해서 str() 이라는 메소드를 만들면 문자열을 반환하는 용으로 사용할 수 았다캄. 그래서 완성된 게
str() 메서드
자료구조 교재 9페이지에 참고
>>> str
<class 'str'>
>>> a=[1, 2, 3]
>>> a.__str__()
'[1, 2, 3]'
>>> a=[1, 2, 3]
>>> str(a)
'[1, 2, 3]'
>>>
!!!!!!!
>>> ai=str()
>>> ai
''
a는 객체가 됨 str클래스로 생성한 것.
이때 str 클래스 안에 든 생성자 함수(문자열 반환 기능)가 적용된 거임.
__main__에 있는 클래스겠지??
>>> __name__
'__main__'
모듈 import 했을 때 물어보면 모듈 이름 나옴 처음엔 main이 기본
__str__()는 그냥 print 하면 그때 적용
기존에 존재했던 문자열 반환 긴으을 오버라이딩해서 내입맛대로 바꿔서 쓸 수 있음.
class Color():
def __init__(self,name):
self.name = name
red = Color('red')
yellow = Color('yellow')
black = Color('black')
arr = [red, yellow, black]
for ar in arr:
print (ar)
<__main__.Color object at 0x00D663E8>
<__main__.Color object at 0x00D66448>
<__main__.Color object at 0x00D66478>
Color 함수를 정의하고 객체를 3개 만들었습니다.
이후 출력을 하였을 때 Color함수의 메모리 주소가 나오게 됩니다.
함수에 str, repr을 정의하지 않았기 때문입니다.
class Color():
def __init__(self,name):
self.name = name
def __str__(self):
return f'__str__: {self.name=}'
def __repr__(self):
return f'__repr__: {self.name=}'
red = Color('red')
yellow = Color('yellow')
black = Color('black')
arr = [red, yellow, black]
for ar in arr:
print (ar)
__str__: self.name='red'
__str__: self.name='yellow'
__str__: self.name='black
str 함수와 repr함수를 추가한 뒤, 출력을 하였을 때 str의 함수가 호출되는 것을 확인할 수 있었습니다.
만약 repr함수만 정의하였을 때는 아래와 같이 출력됩니다.
__repr__: self.name='red'
__repr__: self.name='yellow'
__repr__: self.name='black'
위를 통해 출력을 할 때 str이 repr보다 우선순위가 높다는 것을 알 수 있었습니다.
https://recordnb.tistory.com/47


class counter:
def __init__(self, start=1):
self.value=start
def increase(self):
self.value+=1
return self
c=counter()
c=c.increase().increase()
print(c.value)
retutn self라고 해야됨 객체 전체를 반환. self.value 처럼 객체의 속성만 반환하는 건 X
class counter:
def __init__(self, up, down):
self.num= up
self.den = down
def __str__(self):
return str(self.num)+"/"+str(self.den)
num1= counter(1,4)
num2= counter(1,2)
print(num1)
print(num1.den)
>>> 1/4
4
암것도 안 했는데 저절로 문자열로 변환돼서 나타남 __str__ 됨
클래스 안의 언더스코어(_) 가 달린 메서드는 따로 호출을 안 해도 자동 실행되는 걸 알 수 있다.
10p의 --add-- 와 multiply 메서드를 보면 곱하기 할 떄는 따로 num3=num3.multiply(num2) 이런 식으로 해야 계산이 되는데 add는 걍 바로 나옴

self.속성=어쩌고
하면 다른 메서드에선 이에 접근 가능 (같은 클래스 안에서)