self
란 클래스의 인스턴스를 나타내는 변수
class 내 method 들의 첫번째 인자로 전달됩니다.
class Person:
def sayHello():
print('hi')
man = Person()
man.sayHello()
# TypeError: Person.sayHello() takes 0 positional arguments but 1 was given
# 에러의 뜻은 sayHello 메소드에 argument를 전달했는데 받는 처리를 안해서 문제
class Person:
def sayHello(self):
print('hi')
man = Person()
man.sayHello()
# hi
# self를 sayHello 메소드에 넣으면 정상 수행
id()
함수를 사용해 어디에 있는지 알 수 있습니다.class Person:
def sayHello(self):
print(id(self)) # 2757106068848
print('hi') # hi
man = Person()
man.sayHello()
class Person:
def sayHello(self):
print(id(self))
print('hi')
man = Person()
man.sayHello()
print(id(man))
# 1383514172784
# hi
# 1383514172784
class Person:
def sayHello(self):
print(id(self))
print('hi')
Person.sayHello()
# TypeError: Person.sayHello() missing 1 required positional argument: 'self'
class Person:
def sayHello(self):
print(id(self))
print('hi')
man = Person()
Person.sayHello(man)
print(id(man))
#2363631005040
#hi
#2363631005040
Person.sayHello() 통해 sayHello 매소드가 호출되기는 하나 인스턴스를 통해 호출한 것이 아니라 클래스를 통한 호출이라 Person.sayHello()는 인스턴스를 통한 호출 man.sayHello()과는 조금 다릅니다.
Person.sayHello() 역시 메소드를 정상적으로 호출할 수 있는 것은 마찬가지이기 때문에 인자로 인스턴스를 잘 전달하면 문제없이 수행됩니다.
전달되는 인스턴스는 꼭 Person 객체를 통해 만든 인스턴스가 아니어도 됩니다.
class Person:
def sayHello(self):
print(id(self))
print('hi')
class Robot:
life = 1000
bot = Robot()
man = Person()
Person.sayHello(bot)
print(id(man))
#2866641665088
#hi
#2866643139408
self
는 자기자신Student
: 클래스(붕어빵틀)__init__
: 생성자__init__
을 사용하면 클래스명을 쓰고 옆에 바로 인자들을 채워 넣음으로써 그 값들을 지닌 객체를 만들어 낼 수 있습니다.class Student:
name = ''
korean = 0
english = 0
math = 0
def __init__(self, name, kor, eng, math):
self.name = name
self.korean = kor
self.english = eng
self.math = math
def say_hello(self):
return '안녕하세요 {}님'.format(self.name)
def average(self):
return (self.korean + self.english + self.math) / 3
self
로 사용하는 것이 원칙입니다.hgd = Student('홍길동', 80, 85, 75)
.
을 찍으면 그 인스턴스의 변수에 접근할 수 있습니다.print(hgd.average())
def average(self)
로 선언했는데, 실제로 사용할 때는 self
는 빼고 그냥 hgd.average()
라고 썼습니다. 왜냐하면 클래스의 함수는 선언할 때 첫번째 인자 self
라고 선언하는 것이 원칙이고, 사용할 때는 self
는 무조건 주어지는 것이 파이썬의 원칙이여서 빼고 사용합니다.참고