파이썬에서는 모든 것이 객체로 구현된다.
정수 뿐만 아니라 문자열이나 리스트 역시 객체로 구현되어 있다.
class (클래스 이름):
클래스 내용
...
(인스턴스 이름) = (클래스이름)(매개변수)
__init__(self, 추가적인 매개변수)self를 입력해야함class (클래스이름):
def (메소드이름)(self, 추가적인 매개변수):
(메소드 내용)
__str__(self)class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "이름은 {}이고, 나이는 {}살입니다.".format(self.name, self.age)
def q6():
myDog = Dog('Mango', 3)
print(myDog)
실행 결과
이름은 Mango이고, 나이는 3살 입니다.
상속 이라고 함__<변수 이름> 형태로 선언해주면 됨class Cat:
def __init__(self, name, age):
self.__name = name
self.__age = age
def __str__(self):
return f'Cat(name='{self.__name}', age={self.__age})'
def set_age(self, age):
if age > 0:
self.__age = age
def get_age(self):
return self.__age
nabi = Cat('나비', 3)
print(nabi)
nabi.set_age(4)
nabi.set_age(-5)
print(nabi)
실행 결과
Cat('나비', 3)
Cat('나비', 4)
isinstance(instance, class)
type()을 이용해 알아볼 수도 있음class Human:
def __init__(self):
pass
class Student(Human):
def __init__(self):
pass
student = Student()
print('isinstance(student, Human):', isinstance(student, Human))
print('type(student) == Human:', type(student) == Human)
isinstance(student, Human): True
type(student) == Human: False
__메소드이름__()x + y __add__(self, other)
x - y __sub__(self, other)
x * y __mul__(self, other)
x ** y __pow__(self, other)
x / y __truediv__(self, other)
x // y __floordiv__(self, other)
x % y __mod__(self, other)
+x __pos__(self)
-x __neg__(self)
x < y __lt__(self, other) # Less Then
x <= y __le__(self, other) # Less then or Equal
x >= y __ge__(self, other) # Greater than or Equal
x > y __gt__(self, other) # Greater Than
x == y __eq__(self, other) # EQual
x != y __ne__(self, other) # Not Equal
class (클래스이름):
(클래스 변수) = (값)
클래스 변수에 접근하기
(클래스이름).(변수이름)
>>> n = 100
>>> id(100)
4509016272
>>> id(n)
4509016272
>>> m = n
>>> id(m)
4509016272
>>> n = 200
>>> id(n)
4509015680
>>> n = n+1
>>> id(n)
4509016346