"파이썬 클래스"의 두 판 사이의 차이
DB CAFE
(→파이썬 클래스) |
|||
1번째 줄: | 1번째 줄: | ||
= 파이썬 클래스 = | = 파이썬 클래스 = | ||
− | == 예제 == | + | == 파이썬은 모든 자료형 타입이 class 이다. == |
+ | <source lang=python> | ||
+ | >>> type(3) | ||
+ | <class 'int'> | ||
+ | >>> type(3.1) | ||
+ | <class 'float'> | ||
+ | >>> type('3') | ||
+ | <class 'str'> | ||
+ | >>> type([]) | ||
+ | <class 'list'> | ||
+ | >>> type(()) | ||
+ | <class 'tuple'> | ||
+ | </source> | ||
+ | |||
+ | 심지어 function 도 class로 되어있다. | ||
+ | |||
+ | 파이썬은 java 와 마찬가지로 객체지향 프로그래밍이므로 class의 활용이 매우 중요함. | ||
+ | |||
+ | == class 선언 == | ||
+ | <source lang=python> | ||
+ | class Entity: | ||
+ | |||
+ | pass | ||
+ | </source> | ||
+ | pass 키워드를 사용하면 클래스 내부에 아무것도 넣지 않은 상태로 클래스를 정의할 수 있다. | ||
+ | |||
+ | |||
+ | |||
+ | class 는 java 와 마찬가지로 사용하려면 인스턴스를 생성해야 한다. | ||
+ | <source lang=java> | ||
+ | Entitiy sample = new Entity(); | ||
+ | </source> | ||
+ | 로 자바에서 인스턴스를 생성하고 | ||
+ | |||
+ | python 에서는 | ||
+ | <source lang=python> | ||
+ | >>>> sample = Entity() | ||
+ | |||
+ | type(sample) | ||
+ | <class '__main__.Entity'> | ||
+ | >>>> | ||
+ | </source> | ||
+ | 로 () 를 사용하여 인스턴스를 생성한다고 보면 된다. | ||
+ | |||
+ | == 생성자 == | ||
+ | <source lang=python> | ||
+ | # -*- 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() | ||
+ | </source> | ||
+ | |||
+ | java entity 만들어보고 getter setter 지겹게 만들어 봤다면 | ||
+ | 다음 코드를 따로 설명없이 이해가 된다. | ||
+ | 여기서 좀 확실하게 알고가고 싶다면 | ||
+ | 이것만 기억하면 된다. | ||
+ | |||
+ | |||
+ | |||
+ | java 유저들은 self 가 눈에 밟힐 텐데 self가 바로 Entity 클래스가 만든 sample 인스턴스다. | ||
+ | |||
+ | |||
+ | |||
+ | print로 이 self의 id(self)를 찍어보면 id(sample)과 같은 값이 나오는걸 확인할 수 있다. | ||
+ | |||
+ | |||
+ | |||
+ | == 네임스페이스 == | ||
+ | <source lang=python> | ||
+ | >>> 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 | ||
+ | </source> | ||
+ | |||
+ | |||
+ | class 에 namespace를 설정하면 dir() 와 아래 그림에서 보이는 바와 같이 메모리를 차지한다. | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | >>> s1.__dict__ | ||
+ | {} | ||
+ | >>> s2.__dict__ | ||
+ | {} | ||
+ | |||
+ | |||
+ | |||
+ | >>> s1.market = 'kosdaq' | ||
+ | >>> s1.__dict__ | ||
+ | {'market': 'kosdaq'} | ||
+ | |||
+ | |||
+ | |||
+ | >>> s1.market | ||
+ | 'kosdaq' | ||
+ | >>> s2.market | ||
+ | 'kospi' | ||
+ | |||
+ | |||
+ | |||
+ | 아래서 의아한 점은 s2 는 선언을 안해줬는데 kospi를 가지고 있다. | ||
+ | |||
+ | |||
+ | |||
+ | 이유는 아래 그림에서 설명될 것 같다. | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | |||
+ | |||
+ | |||
+ | 클래스 변수와 인스턴스 변수 | ||
+ | 클래스는 생성자와 소멸자가 있다. | ||
+ | |||
+ | |||
+ | |||
+ | 생성자는 init 이고 소멸자는 del로 표현한다. | ||
+ | |||
+ | |||
+ | <source lang=python> | ||
+ | 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 이 있다. | ||
+ | </source> | ||
+ | |||
+ | |||
+ | 여기서 title을 클래스 변수라고 하고 self 가 붙어있는 변수들을 인스턴스 변수라고 한다. | ||
+ | |||
+ | 나는 처음에 클래스 변수와 인스턴스 변수에 대해서 헷갈렸었는데 위의 내용을 읽어보면 이해가 될거라 생각한다. | ||
+ | |||
+ | |||
+ | |||
+ | 앞의 예제 말고도 더 좋은 예제가 있어서 가지고 와봤다. | ||
+ | <source lang=python> | ||
+ | >>> 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 | ||
+ | </source> | ||
+ | |||
+ | |||
+ | == 클래스 상속 == | ||
+ | <source lang=python> | ||
+ | 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() | ||
+ | </souce> | ||
+ | |||
+ | 위의 내용을 읽었다면 그리고 자바로 개발하는 개발 유저라면 pyhton의 클래스 상속도 바로 이해될 것이다. | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | |||
+ | == 예제 사칙연산 클래스 == | ||
<source lang=python> | <source lang=python> | ||
class ClassCalc: | class ClassCalc: | ||
+ | |||
def __init__(self, first, second): | def __init__(self, first, second): | ||
self.first = first | self.first = first | ||
self.second = second | self.second = second | ||
+ | |||
def setdata(self, first, second): | def setdata(self, first, second): | ||
self.first = first | self.first = first | ||
self.second = second | self.second = second | ||
+ | |||
def add(self): | def add(self): | ||
result = self.first + self.second | result = self.first + self.second | ||
return result | return result | ||
+ | |||
def mul(self): | def mul(self): | ||
result = self.first * self.second | result = self.first * self.second | ||
return result | return result | ||
+ | |||
def sub(self): | def sub(self): | ||
result = self.first - self.second | result = self.first - self.second | ||
return result | return result | ||
+ | |||
def div(self): | def div(self): | ||
result = self.first / self.second | result = self.first / self.second |
2020년 3월 12일 (목) 22:23 판
- DBA { Oracle DBA 명령어 > DBA 초급 과정 > DBA 고급 과정 }
- 튜닝 { 오라클 튜닝 목록 }
- 모델링 { 데이터 모델링 가이드 }
1 파이썬 클래스[편집]
1.1 파이썬은 모든 자료형 타입이 class 이다.[편집]
>>> type(3)
<class 'int'>
>>> type(3.1)
<class 'float'>
>>> type('3')
<class 'str'>
>>> type([])
<class 'list'>
>>> type(())
<class 'tuple'>
심지어 function 도 class로 되어있다.
파이썬은 java 와 마찬가지로 객체지향 프로그래밍이므로 class의 활용이 매우 중요함.
1.2 class 선언[편집]
class Entity:
pass
pass 키워드를 사용하면 클래스 내부에 아무것도 넣지 않은 상태로 클래스를 정의할 수 있다.
class 는 java 와 마찬가지로 사용하려면 인스턴스를 생성해야 한다.
Entitiy sample = new Entity();
로 자바에서 인스턴스를 생성하고
python 에서는
>>>> sample = Entity()
type(sample)
<class '__main__.Entity'>
>>>>
로 () 를 사용하여 인스턴스를 생성한다고 보면 된다.
1.3 생성자[편집]
# -*- 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)과 같은 값이 나오는걸 확인할 수 있다.
1.4 네임스페이스[편집]
>>> 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
1.5 클래스 상속[편집]
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()
</souce>
위의 내용을 읽었다면 그리고 자바로 개발하는 개발 유저라면 pyhton의 클래스 상속도 바로 이해될 것이다.
== 예제 사칙연산 클래스 ==
<source lang=python>
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