_니지 2022. 6. 1. 16:32

 

❗클래스

1. 객체지향 프로그래밍

클래스: 특정한 개체를 만들어내기 위한 설계도라 할 수 있고, 속성과 행동을 결정해둔다

객체: 클래스란 틀에 의해 만들어진 것이고, 속성과 행동으로 이루어져 있다

ex) 클래스=쿠키틀    객체=쿠키

객체지향(Object-Oriented) 프로그래밍: 여러 객체들을 만들고 이것들이 어떻게 움직이고 상호작용하는지에 주목

 

 

2. 클래스 예시

class Car:
    name = ""
    color = ""
    speed = 0
    
    #constructor
    def __init__(self, name, color, speed):
        self.name = name
        self.color = color
        self.speed = speed
    
    def show_info(self):
        print("이름: %s, 색상: %s, 속도: %d" %(self.name, self.color, self.speed))
        
        
    #setter
    def set_name(self, name):
        self.name = name
        
    def set_color(self, color):
        self.color = color

    def set_speed(self, speed):
        self.speed = speed
        
    #getter
    def get_name(self):
        return self.name
    
    def get_color(self):
        return self.color
    
    def get_speed(self):
        return self.speed

 

 

3. 클래스 용어

-생성자

객체를 생성할 때 자동으로 호출되고, 객체의 특징을 결정시켜줌

반드시 첫번째 인수로 self를 지정해야 한다(self 에 인스턴스 자체가 전달됨)

-필드(field): 클래스에 내장된 변수

-메소드(method): 클래스 내부에 선언된 함수

-속성(attribute): 필드 + 메소드

-인스턴스 변수

self가 붙은 변수 -> 인스턴스 자신

 

 

4. 객체와 인스턴스

c1 = Car( )

c1:  객체 -> Car의 인스턴스

인스턴스: 특정 객체가 어떤 클래스의 객체인지를 관계위주로 설명할 때 사용

=> c1은 객체이고, Car의 인스턴스이다

 

 

5. 인스턴스 각 요소에 접근

클래스 안에 getter와 setter를 선언해줌

-변수값을 얻기: getter

-변수값을 지정 또는 수정: setter

 

 

 

 

728x90
반응형