클래스에서 함수를 사용하면 리스트보다 이유를 더욱 명확하게 설명할 수 있다. 아래의 코드처럼 Max와 Lisa는 코드를 작성하고있다는 함수를 잘 불러오고 있다. 하지만 필립은 코드를 작성하고있다고 표현되지 말아야 합니다.(직업이 디자이너 이니깐) 만약 이렇게 함수를 사용하면 누가 와도 이 함수를 불러서 사용할 수 있으므로 클래스 내부에 사용하여 불필요한 함수의 접근을 막을 수 있습니다.
se1 = ["Software Engineer", "Max", 20, "junior", 5000]
se2 = ["Software Engineer", "Lisa", 25, "senior", 5000]
d1 = ["Designer", "Philipp"]
def code(se):
print(f"{se[1]} is writing code...")
code(se1)
code(se2)
code(d1)
아래의 코드처럼 클래스 안에 함수를 선언하고 self.이라는 인스턴스 매서드를 통해서 인스턴스 속성에 접근한다.
class SoftwareEngineer:
alias = "Keyboard Magician"
def __init__(self, name, age, level, salary) :
self.name = name
self.age = age
self.level = level
self.salary = salary
def code(self):
print(f"{self.name} is writing code...")
se1 = SoftwareEngineer("Max", 20, "junior", 5000)
se2 = SoftwareEngineer("Lisa", 25, "senior", 7000)
se1.code()
se2.code()
또한 매개변수도 넘겨서 사용할 수 있다.
class SoftwareEngineer:
alias = "Keyboard Magician"
def __init__(self, name, age, level, salary) :
self.name = name
self.age = age
self.level = level
self.salary = salary
def code(self):
print(f"{self.name} is writing code...")
def code_in_language(self, language):
print(f"{self.name} is writing code in {language}")
se1 = SoftwareEngineer("Max", 20, "junior", 5000)
se2 = SoftwareEngineer("Lisa", 25, "senior", 7000)
se1.code_in_language("Python")
함수에서 인스턴스 속성을 반환할 수 있다.
class SoftwareEngineer:
alias = "Keyboard Magician"
def __init__(self, name, age, level, salary) :
self.name = name
self.age = age
self.level = level
self.salary = salary
def code(self):
print(f"{self.name} is writing code...")
def code_in_language(self, language):
print(f"{self.name} is writing code in {language}")
def information(self):
information = f"Name: {self.name}, Age: {self.age}, Level: {self.level}"
return information
se1 = SoftwareEngineer("Max", 20, "junior", 5000)
se2 = SoftwareEngineer("Lisa", 25, "senior", 7000)
print(se1.information())
기본 정보 출력 메서드, 이전에 information을 이용하여 정보를 출력하였다. 하지만 __str__메서드를 이용하면 아래의 코드처럼 출력해도 기본정보값을 불러온다. 만약 __str__메서드를 사용하지 않고 아래의 코드처럼 출력하면 자료의 주소값이 나온다.
class SoftwareEngineer:
alias = "Keyboard Magician"
def __init__(self, name, age, level, salary) :
self.name = name
self.age = age
self.level = level
self.salary = salary
def code(self):
print(f"{self.name} is writing code...")
def code_in_language(self, language):
print(f"{self.name} is writing code in {language}")
def __str__(self):
information = f"Name: {self.name}, Age: {self.age}, Level: {self.level}"
return information
se1 = SoftwareEngineer("Max", 20, "junior", 5000)
se2 = SoftwareEngineer("Lisa", 25, "senior", 7000)
print(se1)
두 객체를 비교하는 메서드, 아래의 코드처럼 안의 같은 값이 있지만 두개의 인스턴스는 다르다고 나온다. 그 이유는 두개의 인스턴스의 메모리 주소값이 다르기 때문이다.
class SoftwareEngineer:
alias = "Keyboard Magician"
def __init__(self, name, age, level, salary) :
self.name = name
self.age = age
self.level = level
self.salary = salary
def code(self):
print(f"{self.name} is writing code...")
def code_in_language(self, language):
print(f"{self.name} is writing code in {language}")
def __str__(self):
information = f"Name: {self.name}, Age: {self.age}, Level: {self.level}"
return information
se1 = SoftwareEngineer("Max", 20, "junior", 5000)
se2 = SoftwareEngineer("Lisa", 25, "senior", 7000)
se3 = SoftwareEngineer("Lisa", 25, "senior", 7000)
print(se2 == se3)
__eq__함수를 추가하여 아래의 코드를 실행하면 “같다(true)”라는 결과를 얻을 수 있다
class SoftwareEngineer:
alias = "Keyboard Magician"
def __init__(self, name, age, level, salary) :
self.name = name
self.age = age
self.level = level
self.salary = salary
def code(self):
print(f"{self.name} is writing code...")
def code_in_language(self, language):
print(f"{self.name} is writing code in {language}")
def __str__(self):
information = f"Name: {self.name}, Age: {self.age}, Level: {self.level}"
return information
def __eq__(self, other):
return self.name == other.name and self.age == other.age and self.level == other.level and self.salary == other.salary
se1 = SoftwareEngineer("Max", 20, "junior", 5000)
se2 = SoftwareEngineer("Lisa", 25, "senior", 7000)
se3 = SoftwareEngineer("Lisa", 25, "senior", 7000)
print(se2 == se3)