파이썬-py

클래스, 모듈.py

it 킹왕짱 2022. 7. 25. 18:14
728x90
- 클래스를 사용하면 def 함수를 증가 시키지 않아도 객체만 생성하면 함수를 독립적으로 여러번 사용 가능
- 클래스 : 과자 틀 → 똑같은 것을 여러번 생성 가능
- 객체 : 과자 틀에 의해서 만들어진 과자 → 객체마다 고유한 성질을 가짐 즉, 독립적임
객체가 a라면 a는 객체이며 a는 클래스의 인스턴스

- 생성자 : 객체가 생성될 때 자동으로 호출되는 메서드
>>> class Fourcal:
	def setdata(self,first, second):	##클래스 내부 함수를 메서드로 표현
		##self는 객체가 자동으로 전달 self=객체 a
		##객체.메서드 함수 호출시 self 반드시 생략해야함
		self.first=first 		##메서드의 수행문
		self.second=second 		##메서드의 수행문

>>> a=Fourcal()
>>> a.setdata(4,2)
>>> print(a.first,' ',a.second)
4   2
>>> a=Fourcal()
>>> b=Fourcal()
>>> a.setdata(5,6)
>>> b.setdata(9,1)##독립적인 객체
>>> print(a.first, a.second)
5 6
>>> print(b.first, b.second)
9 1

##연산법칙이 있는 클래스
>>> class cal():
	def setdata(self, first,second):
		self.first=first
		self.second=second
	def add(self):
		result=self.first+self.second
		return result
	def sub(self):
		result=self.first-self.second
		return result
	def mul(self):
		result=self.first*self.second
		return result
	def div(self):
		result=self.first/self.second
		return result
>>> a=cal()
>>> a.setdata(9,3) ##생성자 __init__을 하면 바로 a=cal(9,3) 가능
>>> a.add()
12
>>> a.sub()
6
>>> a.mul()
27
>>> a.div()
3.0

##생성자
>>> class cal():
	def __init__(self, first,second): ##이 함수 메서드는 셍성자가 됨
		self.first=first
		self.second=second
	def add(self):
		result=self.first+self.second
		return result
	def sub(self):
		result=self.first-self.second
		return result
	def mul(self):
		result=self.first*self.second
		return result
	def div(self):
		result=self.first/self.second
		return result
 >>> a=cal(4,2)
 >>> print(a.first)
4
>>> a.add()
6

##클래스의 상속
>>> class parent(cal):
	def pow(self):
		result=self.first ** self.second
		return result
>>> a=parent(2,10)
>>> a.pow()
1024

##메서드 오버라이딩
>>> class notzeroerror(cal):
	def div(self):
		if self.second==0:
			return 0
		else:
			return self.first/self.second

		
>>> a=notzeroerror(5,0)
>>> a.div()
0

##클래스 변수
>>> class family:
	lastname='kim'

	
>>> print(family.lastname)
kim
>>> family.lastname='park'
>>> print(family.lastname)
park

 

 

모듈→ 다른 프로그램에서 불러서 쓸 수 있도록 함수, 변수 또는 클래스를 모아놓은 파일
반드시 파일이 저장된 경로로 이동해야함
##module.py
def sum(a,b):
    return a+b

def sub(a,b):
    return a-b

def pro(a,b):
    return a*b

def div(a,b):
    return a/b

import module ##import 모듈이름
print(module.add(2,3))  >>>5

from module import add
add(3,4) >>>7
from module import add, sub
sub(7,3) >>>4

from module import * ## 모든 것 : *


# mod1.py 
def add(a, b): 
    return a+b

def sub(a, b): 
    return a-b

if __name__ == "__main__": ##참이라면
    print(add(1, 4))
    print(sub(4, 2))

##mod2.py
pi=3.141592

class math:
    def sole(self,r):
        return pi*(r**2)
def add(a,b):
    return a+b

print(mod2.add(mod2.pi,4))
728x90
728x90