■ Python Class의 특징
- 멤버가 있으나 자바와는 다르게 멤버변수는 전부 public이다.
■ 클래스의 선언과 생성
class 클래스명:
pass # 빈 클래스임을 나타냄
someone = 클래스명()
■ Python의 생성자
- 두 개의 생성자를 가질 수 없다.
- 생성자 작성 방법
- __init__()은 클래스당 한 개만 작성가능
- self : 클래스 내부에서 __init__() 함수의 첫 매개변수여야 한다.
(키워드가 아니어서 다른 이름을 쓸 수 있지만 self 명칭을 쓰는 것이 관행이다.)
def __int__(self) : # 기본 생성자
def __int__(self, a, b) : # 전달인자 2개 받는 생성자
class FourCal :
def setdata(self, first, second) : # self변수는 객체명을 받는 용도이며, 생략 불가
self.first = first
self.second = second
a = FourCal() # 객체 생성
a.setdata(3, 4); # 첫 번째 호출 방법
b = FourCal()
FourCal.setdata(b, 5, 6) # 두 번째 호출 방법, b 생략 불가
print(a.first, a.second)
print(b.first, b.second)
■ 상속
class 자식클래스명(부모클래스명):
class Car() :
def exclaim(self) :
print("I'm a car")
class Yogo(Car) :
pass
car = Car()
print(car.exclaim()) # I'm a car 출력
yogo = Yogo()
print(yogo.exclaim()) # I'm a car 출력, 메서드 상속됨
class Person() :
def __init__(self, name):
self.name = name
class MDPerson(Person) :
def __init__(self, name) :
self.name = "Doctor " + name
class JDPerson(Person) :
def __init__(self, name) :
self.name = name +", Esquire"
person = Person('Fudd')
doctor = MDPerson('Fudd')
lawer = JDPerson('Fudd')
print(person.name) # Fudd 출력
print(doctor.name) # Doctor Fudd 출력
print(lawer.name) # Fudd, Esquire 출력
■ super()
class Person() :
def __init__(self, name):
self.name = name
class EmailPerson(Person) :
def __init__(self, name, email) :
super().__init__(name) # 부모클래스의 __init__() 호출
self.email = email
bob = EmailPerson('박길동', 'bob@frapples.com')
print(bob.name)
print(bob.email)
■ self 키워드
■ 접근지정자
- 파이썬은 멤버의 접근지정자 개념이 없다. (기본적으로 public)
- __(언더스코어 2개) 는 private, _(언더스코어 1개) protected
- 아무것도 없을 때에는 public이라고 약속했으나 크게 의미는 없음
■ setter / getter
- 파이썬에는 private 멤버의 개념이 없으나 멤버 이름을 감춘 것 같은 효과를 줄 수는 있다.
- 프로퍼티를 이용하면 특정 값을 읽거나 할당할 때 항상 특정 메서드가 실행될 수 있도록 강제할 수 있다.
- property() 함수를 이용한 방법
- @ 이용한 방법
getter 메서드 앞 : @property
setter 메서드 앞 : @<필드명>.setter
댓글 영역