Object Oriented Programming
python에서 class는 data type으로 본다.
1. Class와 Object
class
- a user-defined prototype for an object
- 틀(class) -> 제품 (instance/object)
class 특징
1) Encapsulation
불필요한 detail을 감추는 것
2) Polymorphism( =! Compile이 아니라, runtime에 자동적으로
obejct의 type에 따라 자동으로 작업내용이 달라지는 것
3) Inheritance: Class - subclass, Parent-child
2. Class와 Type
1) Class 만들기
- constructor
- initializer
2) Attribute와 Method
- Attribute = Obejct의 성격/특징을 표현하는 변수
- Method = Object에 속한 (bound) 함수
= A special kind of function that is defined in a class detinition.
- Operator overloading: 특정 operator에 여러 개의 함수를 assign하는 것
3) Class namespace
- private; (attribute 또는 method가) object 내에서만 인식되도록 한 것
이 경우에는 accessor method를 통해서만 이용 가능
4) Superclass와 subclass
class SubClassName (ParentClass1[, ParentClass2, ...]):
'OPtional class documentation string'
class_suite
5) Interface와 Introspection
Interface: class간의 관계를 맺을 때(composition)
6) Built-in class attributes
Class attribute | 설명 |
__dict__ | Dictionary containing the class's namespace. |
__doc__ | Class documentation string or None if undefined. |
__name__ | Class name |
__module__ | module name in which the class is defined. This attribute is "__main__" in interactive mode. |
__bases__ | A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list. |
7) Sameness vs. "=="
실체가 같은지 vs. 값이 같은지
8) 복제(copying)
- Aliasing을 했을때 한 쪽의 변경사항이 다른 한쪽에 미치는지가 애매할 수 있다.
- 복제 (copying)이 한 대안이 될 수 있음)
import copy
copy.copy()
예제
class Person:
# 첫째 parameter는 항상 self
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
print("Hello!, I'm %s" % self.name)
personA = Person()
personB = Person()
personA.setName("jiyoung")
personB.setName("babo")
personA.greet() # Hello!, I'm jiyoung
personB.greet() # Hello!, I'm babo
class Point:
""" Point class: represents and manipulates x, y coord."""
def __init__(self):
"""Create a new point at the origin"""
self.x = 0
self.y = 0
p1 = Point()
p2 = Point()
p2.x = 3
p2.y = 5
print("p2's coordinates: ", p2.x, p2.y)
# p2's coordinates: 3 5
hasattr/getattr/setattr/delattr (임시!)
class Employee:
"""Common base class for all employee"""
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee: {}".format(Employee.empCount))
def displayEmployee(self):
print("Name: ", self.name, ", Salary: ", self.salary)
emp1 = Employee("jiyoung", 200)
emp2 = Employee("babo", 100)
emp1.displayCount() # Total Employee: 2
emp1.displayEmployee() # Name: jiyoung , Salary: 200
# 추가하거나 지우는 것도 가능하다 (임시)
emp1.age = 20
print(hasattr(emp1, 'age')) # True
print(getattr(emp1, 'age')) # 20
setattr(emp1, 'age', 20)
delattr(emp1, 'age')
Private
__를 쓰면 private method가 됨
# Private
class PrivateTest():
def __inaccessible(self):
print('Not permitted to us from outside the object')
def accessible(self):
print('Permiited to access')
self.__inaccessible()
t1 = PrivateTest()
# t1.__inaccessible()
# AttributeError: 'PrivateTest' object has no attribute '__inaccessible'
t1.accessible()
# Permiited to access
# Not permitted to us from outside the object
Encapsulate의 예라고 할수 있음
Inheritance
class Parent:
parenAttr = 100
def __init__(self):
print("Calling parent constructor")
def perentMethod(self):
print("Calling parent method")
def setAttr(self, attr):
Parent.parenAttr = attr
def getAttr(self):
print("Parent attribute:", Parent.parenAttr)
# Inheritance
class Child(Parent):
def __init__(self):
print("Calling child constructor")
def childMethod(self):
print("Calling child method")
c = Child()
# Calling child constructor
c.childMethod()
# Calling child method
c.perentMethod()
# Calling parent method
c.setAttr(200)
c.getAttr()
# Parent attribute: 200
multiple Inheritance: python은 다중상속이 가능
class Calculator:
def calculate(self, expression):
self.value = eval(expression)
class Talker:
def talk(self):
print("Hi my value is", self.value)
class TalkingCalcuator(Calculator, Talker):
pass
tc = TalkingCalcuator()
tc.calculate('2+7')
tc.talk()
# Hi my value is 9
'Data > python·알고리즘' 카테고리의 다른 글
[python] 알아두면 좋은 Standard Library (0) | 2018.06.29 |
---|---|
[python 기초] Exception 처리 (0) | 2018.06.29 |
[python 기초] python의 file mode (0) | 2018.06.29 |
[python 기초] python의 함수에 대하여 (0) | 2018.06.28 |
[python 기초] python의 module에 대하여 (0) | 2018.06.28 |
댓글