다른 명령
새 문서: = 파이썬 클래스 = == 용어 == {{틀:고지상자 |제목=용어 설명 |내용=* class : 멤버와 메쏘드를 갖는 객체 * class instance : 클래스를 호출하여 만들어지는 객체 * member : 클래스의 변수 * method : 클래스의 함수 * attribute: 속성, 멤버 와 메쏘드의 전체 * supperclass : base class라고 하며 최상위 클래스 * subclass : derived class라고 하며 수퍼클래스로터 상속된 하위 클래스 * inheritance :... |
|||
(같은 사용자의 중간 판 5개는 보이지 않습니다) | |||
1번째 줄: | 1번째 줄: | ||
= 파이썬 클래스 = | == 파이썬 클래스 == | ||
== 용어 == | === 용어 === | ||
{ | '''용어 설명''' | ||
| | {| class="wikitable" | ||
| | |- | ||
! 용어 !! 설명 | |||
|- | |||
| class || 멤버와 메쏘드를 갖는 객체 | |||
|- | |||
| class instance || 클래스를 호출하여 만들어지는 객체 | |||
|- | |||
| member || 클래스의 변수 | |||
|- | |||
| method || 클래스의 함수 | |||
|- | |||
| attribute || 속성, 멤버와 메쏘드의 전체 | |||
|- | |||
| supperclass || base class라고 하며 최상위 클래스 | |||
|- | |||
| subclass || derived class라고 하며 수퍼클래스로부터 상속된 하위 클래스 | |||
|- | |||
| inheritance || 상속, A클래스를 수퍼클래스로 하는 클래스 B는 B is-a A 관계라고 함 | |||
|- | |||
| Multiple Inheritance || 다중상속, 두 개 이상의 클래스로부터 상속 받음 | |||
|- | |||
| Polymorphism || 다형성, 상속관계 내의 다른 클래스의 인스턴스들이 같은 멤버 함수 호출에 대해 각각 다르게 반응하도록 하는 기능 | |||
|- | |||
| Encapsulation || 은닉, 메쏘드와 멤버를 클래스 내에 포함시키고 외부에서 접근할 수 있도록 인터페이스만을 공개하고 다른 속성은 숨기는 것 | |||
|- | |||
| Composition || 합성, X라는 객체가 클래스 A 안에 포함되어 A의 각종 메소드를 구현하는데 사용됨. A가 x를 포함하므로 has-a 관계라 함 | |||
|} | |||
== 파이썬은 모든 자료형 타입은 class 이다. == | === 파이썬은 모든 자료형 타입은 class 이다. === | ||
<source lang=python> | <source lang=python> | ||
>>> type(3) | >>> type(3) | ||
35번째 줄: | 49번째 줄: | ||
파이썬은 java 와 마찬가지로 객체지향 프로그래밍이므로 class의 활용이 매우 중요함. | 파이썬은 java 와 마찬가지로 객체지향 프로그래밍이므로 class의 활용이 매우 중요함. | ||
== 클래스 선언 == | === 클래스 선언 === | ||
<source lang=python> | <source lang=python> | ||
class Entity: | class Entity: | ||
59번째 줄: | 73번째 줄: | ||
로 () 를 사용하여 인스턴스를 생성한다고 보면 된다. | 로 () 를 사용하여 인스턴스를 생성한다고 보면 된다. | ||
== 생성자 == | === 생성자 === | ||
<source lang=python> | <source lang=python> | ||
221번째 줄: | 235번째 줄: | ||
</source> | </source> | ||
== 클래스 상속 == | === 클래스 상속 === | ||
<source lang=python> | <source lang=python> | ||
class Parent: | class Parent: | ||
248번째 줄: | 262번째 줄: | ||
위의 내용을 읽었다면 그리고 자바로 개발하는 개발 유저라면 pyhton의 클래스 상속도 바로 이해될 것이다. | 위의 내용을 읽었다면 그리고 자바로 개발하는 개발 유저라면 pyhton의 클래스 상속도 바로 이해될 것이다. | ||
== 예제 사칙연산 클래스 == | === 예제 사칙연산 클래스 === | ||
<source lang=python> | <source lang=python> | ||
class ClassCalc: | class ClassCalc: |
2025년 6월 28일 (토) 15:51 기준 최신판
파이썬 클래스
용어
용어 설명
용어 | 설명 |
---|---|
class | 멤버와 메쏘드를 갖는 객체 |
class instance | 클래스를 호출하여 만들어지는 객체 |
member | 클래스의 변수 |
method | 클래스의 함수 |
attribute | 속성, 멤버와 메쏘드의 전체 |
supperclass | base class라고 하며 최상위 클래스 |
subclass | derived class라고 하며 수퍼클래스로부터 상속된 하위 클래스 |
inheritance | 상속, A클래스를 수퍼클래스로 하는 클래스 B는 B is-a A 관계라고 함 |
Multiple Inheritance | 다중상속, 두 개 이상의 클래스로부터 상속 받음 |
Polymorphism | 다형성, 상속관계 내의 다른 클래스의 인스턴스들이 같은 멤버 함수 호출에 대해 각각 다르게 반응하도록 하는 기능 |
Encapsulation | 은닉, 메쏘드와 멤버를 클래스 내에 포함시키고 외부에서 접근할 수 있도록 인터페이스만을 공개하고 다른 속성은 숨기는 것 |
Composition | 합성, X라는 객체가 클래스 A 안에 포함되어 A의 각종 메소드를 구현하는데 사용됨. A가 x를 포함하므로 has-a 관계라 함 |
파이썬은 모든 자료형 타입은 class 이다.
>>> type(3) <class 'int'> >>> type(3.1) <class 'float'> >>> type('3') <class 'str'> >>> type([]) <class 'list'> >>> type(()) <class 'tuple'>
심지어 function 도 class로 되어있다.
파이썬은 java 와 마찬가지로 객체지향 프로그래밍이므로 class의 활용이 매우 중요함.
클래스 선언
class Entity: pass
pass 키워드를 사용하면 클래스 내부에 아무것도 넣지 않은 상태로 클래스를 정의할 수 있다.
class 는 java 와 마찬가지로 사용하려면 인스턴스를 생성해야 한다.
Entitiy sample = new Entity();
로 자바에서 인스턴스를 생성하고
python 에서는
>>>> sample = Entity() type(sample) <class '__main__.Entity'> >>>>
로 () 를 사용하여 인스턴스를 생성한다고 보면 된다.
생성자
# -*- coding: utf-8 -*- class Entitiy: def __init__(self,name, email, phone): self.name = name self.email = email self.phone = phone def pring_info(self): print("Name : ", self.name) print("E-mail :", self.email) print("phone : ", self.phone) sample = Entitiy("dbcafe","test@gmail.com","01012345678") sample.pring_info()
java entity 만들어보고 getter setter 지겹게 만들어 봤다면 다음 코드를 따로 설명없이 이해가 된다. 여기서 좀 확실하게 알고가고 싶다면 이것만 기억하면 된다.
java 유저들은 self 가 눈에 밟힐 텐데 self가 바로 Entity 클래스가 만든 sample 인스턴스다.
print로 이 self의 id(self)를 찍어보면 id(sample)과 같은 값이 나오는걸 확인할 수 있다.
생성자 와 소멸자
__init__ #생성자
__del__ #소멸자
네임스페이스
>>> class Stock: market = "kospi" >>> dir() ['Stock', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] >>> Stock.market 'kospi' >>> s1 = Stock() >>> s2 = Stock() >>> id(s1) 50572464 >>> id(s2) 50348240
class 에 namespace를 설정하면 dir() 와 아래 그림에서 보이는 바와 같이 메모리를 차지한다.
>>> s1.__dict__
{}
>>> s2.__dict__
{}
>>> s1.market = 'kosdaq' >>> s1.__dict__ {'market': 'kosdaq'}
>>> s1.market 'kosdaq' >>> s2.market 'kospi'
아래서 의아한 점은 s2 는 선언을 안해줬는데 kospi를 가지고 있다.
이유는 아래 그림에서 설명될 것 같다.
클래스 변수와 인스턴스 변수 클래스는 생성자와 소멸자가 있다.
생성자는 init 이고 소멸자는 del로 표현한다.
class Entitiy: title = "test" def __init__(self,name, email, phone): self.name = name self.email = email self.phone = phone def __del__(self): Entitiy.title def pring_info(self): print("Name : ", self.name) print("E-mail :", self.email) print("phone : ", self.phone)
Entity 클래스에는 title 변수와 name / email / phone 이 있다. 여기서 title을 클래스 변수라고 하고 self 가 붙어있는 변수들을 인스턴스 변수라고 한다.
나는 처음에 클래스 변수와 인스턴스 변수에 대해서 헷갈렸었는데 위의 내용을 읽어보면 이해가 될거라 생각한다.
앞의 예제 말고도 더 좋은 예제가 있어서 가지고 와봤다.
>>> class Account: num_accounts = 0 def __init__(self, name): self.name = name Account.num_accounts += 1 def __del__(self): Account.num_accounts -= 1 >>> >>> kim = Account("kim") >>> lee = Account("lee") >>> kim.num_accounts 2 >>> lee.num_accounts 2 >>> Account.num_accounts 2
클래스 상속
class Parent: def money(self): print("i have money") mother = Parent() mother.money() class Child(Parent): pass child = Child() child.money() #################### class Child2(Parent): def money(self): print("i have plus money") child = Child2() child.money()
위의 내용을 읽었다면 그리고 자바로 개발하는 개발 유저라면 pyhton의 클래스 상속도 바로 이해될 것이다.
예제 사칙연산 클래스
class ClassCalc: def __init__(self, first, second): self.first = first self.second = second 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