본문 바로가기

Python_Beginer/Study

HRD 수업>파이썬을 이용한 자동화 스크립트 - 연습문제 14

반응형
'''
클래스
1. Car 클래스 생성 / 내부는 pass 키워드로 처리
2. member variable을 만든다.
    - pass 키워드를 제거하고, condition 변수를 만들고 'New' 값을 할당한다.
    - my_car라는 Car 객체를 생성하고 멤버변수 condition 값을 print 한다.
3. 객체가 생성될 때마다 호출되는 생성자(__init__)를 만든다.
    - 4개의 파라미터를 받는다 - self, model, color, mpq
    - 생성자를 통해 객체를 생성한다.
4. 멤버변수에 접근한다.
    - my_car 객체의 멤버변수 3개를 각각 print 한다.
5. 메소드를 만들어본다.
    - Car 클래스 안에 display_car() 메소드를 만든다.
    - 스트링을 리턴한다. - 'This is a [color][model] with [mpg] MPG.'
    - my_car 객체에서 display_car() 메소드를 호출하여 print 한다.
6. 클래스 멤버변수에 접근한다.
    - drive_car 메소드를 추가해서 condition 값을 'used'로 바꾸고 값을 print 한다.
7. Car클래스를 상속받아 ElectricCar를 만들고 __init__ 생성자에 'battery_type' 변수를 추가한다.
'''
class Car(object):
    def __init__(self, model, color, mpg):
        # pass
        self.model = model
        self.color = color
        self.mpg = mpg

    def my_car(*args):
        condition = 'New'
        # print(condition + ' model = {0}'.format(self.model))
        # print(condition + ' color = {0}'.format(self.color))
        # print(condition + ' mpg = {0}'.format(self.mpg))
        Car.display_car(*args)

    def display_car(self):
        message = 'This is a {color} {model} with {mpg} MPG.'.\
            format(color = self.color, model = self.model, mpg=self.mpg)
        return print(message)

    def drive_car(my_car):
        my_car.condition = 'used'
        print(my_car.condition)

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        self.model = model
        self.color = color
        self.mpg = mpg
        self.battery_type = battery_type

    def display_car(self):
        message = 'This is a {color} {model} with {mpg} MPG. Bettery type {battery_type}.'\
            .format(color = self.color, model = self.model, mpg=self.mpg, battery_type=self.battery_type)
        return print(message)


car = Car('Samsung 505', 'black', 22)
car.my_car()
car.drive_car()

car_full = ElectricCar('Samsung 505', 'black', 22, 'Lithium-ion')
car_full.display_car()

 

This is a black Samsung 505 with 22 MPG.
used
This is a black Samsung 505 with 22 MPG. Bettery type Lithium-ion

Process finished with exit code 0

반응형