객체마다 고유한 성격을 가지며, 각 객체가 변하더라도 다른 객체에는 아무 영향을 주지 않음
>>> class Cookie:
>>> pass
>>> a = Cookie()
>>> b = Cookie()
class FourCal:
def setdata(self, first, second):
self.first = first
self.second = second
>>> a = FourCal()
>>> a.setdata(4, 2)

>>> class FourCal:
... def setdata(self, first, second):
... self.first = first
... self.second = second
... def add(self):
... result = self.first + self.second
... return result
... def mul(self):
... result = self.first * self.second
... return result
... def sub(self):
... result = self.first - self.second
... return result
... def div(self):
... result = self.first / self.second
... return result
>>> a = FourCal()
>>> b = FourCal()
>>> a.setdata(4, 2)
>>> b.setdata(3, 8)
>>> a.add()
6
>>> a.mul()
8
>>> a.sub()
2
>>> a.div()
2
>>> b.add()
11
>>> b.mul()
24
>>> b.sub()
-5
>>> b.div()
0.375
객체가 생성될 때 자동으로 호출되는 메서드
__init__을 사용하면 해당 메서드는 생성자가 됨>>> class FourCal:
... def __init__(self, first, second):
... self.first = first
... self.second = second
... def add(self):
... result = self.first + self.second
... return result
... def mul(self):
... result = self.first * self.second
... return result
... def sub(self):
... result = self.first - self.second
... return result
... def div(self):
... result = self.first / self.second
... return result
...
>>> a = FourCal(4, 2)
>>> a.first
4
>>> a.second
2
>>> a = FourCal(4, 2)
>>> a.add()
6
>>> a.div()
2.0
class 클래스이름(상속할 클래스 이름)
>>> class MoreFourCal(FourCal):
... def pow(self):
... result = self.first ** self.second
... return result
>>> a = MoreFourCal(4, 2)
>>> a.add()
6
>>> a.mul()
8
>>> a.sub()
2
>>> a.div()
2
>>> a.pow()
16
>>> class Family:
... lastname = "김"
>>> Family.lastname
김
>>> a = Family()
>>> b = Family()
>>> Family.lastname = "박"
>>> a.lastname
박
>>> b.lastname
박
>>> a.lastname = "최"
>>> a.lastname
최
>>> Family.lastname
박
>>> b.lastname
박
파이썬 확장자(.py)로 만든 파일은 모두 모듈로 사용가능
import 모듈이름
from 모듈이름 import 함수이름, 함수이름
# mod1.py
def add(a, b):
return a+b
def sub(a, b):
return a-b
print(add(1, 4))javascript:page(30)
print(sub(4, 2))
C:\doit>python mod1.py
5
2
# mod1.py
def add(a, b):
return a+b
def sub(a, b):
return a-b
if __name__ == "__main__":
print(add(1, 4))
print(sub(4, 2))
>>> import mod1
>>> mod1.__name__
'mod1'
# mod2.py
PI = 3.141592
class Math:
def solv(self, r):
return PI * (r ** 2)
def add(a, b):
return a+b
>>> import mod2
>>> print(mod2.PI)
3.141592
>>> a = mod2.Math()
>>> print(a.solv(2))
12.566368
>>> print(mod2.add(mod2.PI, 4.4))
7.541592
game/
__init__.py
sound/
__init__.py
echo.py
wav.py
graphic/
__init__.py
screen.py
render.py
play/
__init__.py
run.py
test.py