프로그래밍/Python
python 5일차 - OOP, 클래스
비전공개미
2022. 9. 2. 17:54
반응형
SMALL
In [3]:
'''
OOP (Object Oriented Programing)
변수(저장), 함수(처리)
일반변수, tuple(변경불가능한 리스트), list, dictionary(자바의 map)
list 접근 : index number 0 ~ length-1 -> 번호(숫자), <선형구조>
dictionary 접근 : key(string) : value, <트리구조>
OOP (Object Oriented Programing)
class
변수(멤버)
초기화 함수 __init__
함수(멤버) -> method
'''
class Car:
def __init__(self):
print('Car __init__')
car = Car()
car.__init__() # 자바와는 다르게 따로 호출이 가능하다
Car __init__
Car __init__
In [7]:
'''
OOP의 3대 특징(요소)
은닉성(캡슐화) - 파이썬에서는 해당X
상속성
다형성 - 파이썬에서는 해당X
'''
class Car:
def __init__(self, color, year):
self.color = color # self.변수 == 멤버변수
self.year = year
def getColor(self):
return self.color # 파라메타 값이 하나면 self. 를 생략해도 됨
def setColor(self, color):
self.color = color
# getColor, setColor를 사용하게 만드는것을 은닉성이라 함
benz = Car('white', 2021)
print(benz)
bmw = Car('blue', 2020)
print(bmw)
## benz와 bmw는 다른변수이며 자기자신 self로 구분한다
# benz.color
benz.setColor('balck')
benz.getColor()
<__main__.Car object at 0x00000252BC8DA310>
<__main__.Car object at 0x00000252BC8DA0A0>
Out[7]:
'balck'
In [12]:
class BaseProc:
def dataInput(self, num1, num2):
self.num1 = num1
self.num2 = num2
# self.oper = oper
def plus(self):
return self.num1 + self.num2
def minus(self):
return self.num1 - self.num2
'''
proc = BaseProc() # 객체생성
proc.dataInput(10, 15) # 데이터 입력
result = proc.plus() # 연산
result
'''
# 클래스 상속
class Calculator(BaseProc): # BaseProc은 부모클래스 / Calculator는 자식클래스
# pass
def multi(self):
return self.num1 * self.num2
def div(self):
return self.num1 / self.num2
cal = Calculator()
cal.dataInput(25, 5)
result = cal.div()
result
Out[12]:
5.0
In [14]:
### self -> 자기 자신의 주소
### super -> 부모 클래스의 주소
class Parent:
def __init__(self):
print('Parent의 __init__')
class Child(Parent):
def __init__(self):
super().__init__() # 부모클래스에 있는 __init__함수를 호출 / super()는 부모클래스의 함수를 호출한다
print('Child의 __init__')
ch = Child()
Parent의 __init__
Child의 __init__
In [26]:
class Human:
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height
class Pitcher(Human):
def __init__(self, defence, win, lose, name, age, height): # name, age, height의 부모클래스의 값을 가져온다
super().__init__(name, age, height) # super init에 name, age, height 값을 가져온다
self.defence = defence
self.win = win
self.lose = lose
def printing(self):
print('투수 :', self.name, self.age, self.height, self.defence, self.win, self.lose)
class Batter(Human):
def __init__(self, batavg, bat, hit, name, age, height):
super().__init__(name, age, height)
self.batavg = batavg
self.bat = bat
self.hit = hit
def printing(self):
print('타자 :', self.name, self.age, self.height, self.batavg, self.bat, self.hit)
baseballteam = [] # 선수들을 모아줄 리스트
pit = Pitcher(0.23, 10, 3, '박찬호', 30, 181.3)
# pit.printing()
baseballteam.append(pit)
bat = Batter(0.312, 15, 5, '이승엽', 16, 182.5)
baseballteam.append(bat)
# bat.printing()
bat = Batter(0.275, 12, 3, '김태균', 20, 185.5)
baseballteam.append(bat)
for obj in baseballteam:
obj.printing()
투수 : 박찬호 30 181.3 0.23 10 3
타자 : 이승엽 16 182.5 0.312 15 5
타자 : 김태균 20 185.5 0.275 12 3
In [38]:
### 변수의 범위
'''
member variable(변수) -> self.num # 멤버변수의 영역은 class 내부
매개변수(parameter) -> num # 밖에서 값을 받아올때만 사용가능
local(지역) variable(변수) -> number
class(=global) variable(변수) -> clsnumber : 여러 객체가 있어도 하나의 영역이다
'''
class MyClass:
clasnumber = 0
def method(self, _num):
self.num = _num
number = 1
def func(self):
print(self.num)
cls = MyClass()
cls.method(11)
# cls.number ## 오류(영역이 아님)
# cls.num = 11
# print(cls.clsnumber)
MyClass.clsnumber = 11
a = MyClass()
a.method(22)
# print(a.clsnumber)
b = MyClass()
b.method(33)
# print(b.clsnumber)
# 멤버 변수
cls.func()
a.func()
b.func()
# 클래스 변수
cls.clsnumber = 100
a.clsnumber = 200
b.clsnumber = 300
print(cls.clsnumber)
print(a.clsnumber)
print(b.clsnumber)
print(MyClass.clsnumber) # class명.변수 로 접근해야한다(이 방법으로 사용하기)
11
22
33
100
200
300
11
반응형
LIST