C-log

Welcome to Python : 클래스 본문

📘Python

Welcome to Python : 클래스

4:Bee 2023. 7. 21. 23:04
728x90

Title Code Console
클래스를 사용하지 않은 함수

result
= 0


def add(num):
    global result
    result += num
    return result


print(add(3))
print(add(4))
 
3
7
클래스의 기본 구조

class
Calculator:
    def __init__(self):
        self.result = 0

    def add(self, num):
        self.result += num
        return self.result


cal1 = Calculator()
cal2 = Calculator()

print(cal1.add(3))
print(cal1.add(4))
print(cal1.add(3))
print(cal1.add(7))
 
3
7
10
17
간단한 계산기 만들기

class
FourCal:
    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


a = FourCal()
b = FourCal()
a.setdata(4, 2)
b.setdata(3, 8)

print(a.add())
print(a.sub())
print(b.add())
print(b.mul())
6
2
11
24
클래스 생성자

class
FourCal:
    def __init__(self, first, second):
        self.first = first
        self.second = second

    ...

a = FourCal(4, 2)
print(a.first)
print(a.second)
print(a.add())
print(a.div())
4
2
6
2.0
클래스 상속

class
FourCal:
    def __init__(self, first, second):
        self.first = first
        self.second = second

   
...


class MoreFourCal(FourCal):
    pass


a = MoreFourCal(4, 2)
print(a.first)
print(a.second)
print(a.add())
print(a.div())
4
2
6
2.0
메서드 오버라이딩

class
FourCal:
    def __init__(self, first, second):
        self.first = first
        self.second = second

    ...

class SafeFourCal(FourCal):
    def div(self):
        if self.second == 0:
            return 0
        else:
            return self.first / self.second


a = SafeFourCal(4, 0)
print(a.div())


0
클래스 변수
 
class
Family:
    lastname = "김"


print(Family.lastname)
 
 
class
Family:
    lastname = "김"


a = Family()
b = Family()
print(a.lastname)
print(b.lastname)

 
class
Family:
    lastname = "김"


a = Family()
b = Family()

Family.lastname = "박"
print(a.lastname)
print(b.lastname)
 

728x90

'📘Python' 카테고리의 다른 글

Welcome to Python : 패키지  (0) 2023.07.24
Welcome to Python : 모듈  (0) 2023.07.24
Welcome to Python : 프로그램의 입출력  (0) 2023.07.13
Welcome to Python : 파일 읽고 쓰기  (0) 2023.07.13
Welcome to Python : 사용자 입출력  (0) 2023.07.13
Comments