def 함수명(매개변수):
실행문1
실행문2
pass
def sum2(a,b):
print("+ : ",a+b)
print("- : ",a-b)
print("* : ",a*b)
print("/ : ",a/b)
# 함수명 사용 호출
sum2(10,20)
+: 30
-: -10
*: 200
/: 0.5
def myABS(num):
if num<0:
num=-num
return num
print("절대값 ",myABS(1000))
print("절대값 ",myABS(-1000))
# 리턴값없는 리턴문 => 함수의 종료
def test():
return
절대값 1000
절대값 1000
list3 = [1,2,3,4,5,200,30,400]
def listck(v):
print("전달값 ",v)
check="없음"
for i in v:
if i == 100:
check="있음"
break
else:
check="없음"
print("숫자"+check)
def listck2(v):
if 100 in v:
print("숫자 있음")
else:
print("숫자 없음")
전달값 [1, 2, 3, 4, 5, 200, 30, 400]
숫자없음
숫자 없음
# def 함수명(*매개변수):
# 실행문
def test(*v):
print(v)
test(1)
test(1,2)
test(1,2,3,3,5,1,2,4,5)
(1,)
(1, 2)
(1, 2, 3, 3, 5, 1, 2, 4, 5)
def test2(name,age,tel="010-1234-7894"):
print("name",name)
print("age",age)
print("tel",tel)
test2("홍길동",20)
test2("홍길동",20,"010-1212-1212")
name 홍길동
age 20
tel 010-1234-7894
name 홍길동
age 20
tel 010-1212-1212
클래스 선언
class 클래스명:
변수1
변수2
함수1()
함수2()
# 클래스 생성 -> 객체 생성 (생성자 호출)
class Itwill:
clasroom = 5
def study(self):
print("자습")
# 객체 생성
will = Itwill()
will.study()
print(will.clasroom)
자습
5
class MyCalc:
def mySum(self,a,b):
print(" + :",a+b)
def mySub(self,a,b):
print(" - :",a-b)
def myMul(self,a,b):
print(" * :",a*b)
def myDiv(self,a,b):
print(" / :",a/b)
c = MyCalc()
c.mySub(100,200)
print(c)
-:-100
<__main__.MyCalc object at 0x00000270BB258760>
생성자 : 객체 생성시 변수를 초기화
self : 객체 자신의 정보를 가지고있는 레퍼런스(this)
class 클래스명:
def __init__(self):
pass
def __init__(self,name,age):
self.name =name
pass
class ItwillStudent:
name=""
tel=""
# 생성자
def __init__(self):
self.name="기본학생"
self.tel="010-xxxx-xxxx"
def __init__(self,name,tel):
self.name=name
self.tel = tel
def showMyInfo(self):
print("이름 : "+str(self.name)+" 전화번호 : "+self.tel)
kim = ItwillStudent("홍길동","010-1111-2223")
kim.showMyInfo()
이름 : 홍길동 전화번호 : 010-1111-2223
class Parent:
def pprn(self):
print("부모-pprn()")
class Child(Parent):
def cprn(self):
print("부모-cprn()")
def pprn(self):
print("부모-pprn()") #오버라이딩
p = Parent()
p.pprn()
# p.cprn() : x
c = Child()
c.cprn()
c.pprn() #상속했기 때문에 부모의 기능/속성을 사용가능
부모-pprn()
부모-cprn()
부모-pprn()
class Parent:
name="홍길동" # 클래스변수 (인스턴스 변수)
def pprn(self):
print("부모-pprn()")
class Child(Parent):
def cprn(self):
print("자식-cprn()")
def pprn(self):
super().pprn() # super() 부모객체의 생성자 호출
print("자식-pprn()")
부모-pprn()
자식-cprn()
부모-pprn()
자식-pprn()