day 14 making an n dice

3 minute read

making a dice widget

what is OOP?

Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the doc string defined in the function’s source code. The sys module is an object which has (among other things) an attribute called path. And so forth.

  • 파이썬에서는 모든 것(부울, 정수, 실수, 데이터구조(list,tuple,dict,set…), 함수, 프로그램, 모듈)이 객체다.

  • 객체는 상태(state)를 나타내는 속성(attribute)과 동작(behavior)을 나타내는 메소드(method)가 있다.

  • 객체의 속성은 변수로 구현된다. 객체의 메소드는 함수로 구현된다.

class instance

class Car:
    pass

class Car():
    pass

#id(Car)는 여러번 호출해도 같은 값이 얻어집니다. 
print(id(Car))
print(id(Car))

#id(Car())는 Car()가 호출될 때마다 다른 값이 얻어집니다. 
print(id(Car()))
print(id(Car()))

# 두 객체의 type을 살펴봅니다. 
print(type(Car))
print(type(Car()))
2751218617776
2751218617776
2751228877600
2751228878176
<class 'type'>
<class '__main__.Car'>

To call a class, we use the keyword ‘class’ + name + ‘:’

class attribute and method

class Car:
    color = 'red'
    category = 'sports car'

    def drive(self):
        print("I'm driving")

    def accel(self, speed_up, current_speed=10):
        self.speed_up = speed_up
        self.current_speed = current_speed + speed_up
        print("speed up", self.speed_up, "driving at", self.current_speed)
mycar = Car()
print(mycar.color)
red
mycar.drive()
mycar.accel(5)
I'm driving
speed up 5 driving at 15
Car.drive(mycar)
I'm driving

image using self parameter, we can call car like below image

class Test:
    def run1(self):
        print("run1")

    def run2():
        print("run2")

t = Test()
t.run1()
run1
class Test2:
    def run1(self, a):
        self.a = float(a) * 10
        print(self.a)

    def run2(self, b):
        b = float(b) + 10
        print(self.b)
        
t = Test2()
t.run1(1)
10.0
  • self는 자기 자신입니다.

  • 클래스에 의해 생성된 객체(인스턴스)를 가리킵니다.

  • 클래스의 메서드는 인자로 해당 인스턴스(self)를 받아야 합니다.

  • 메소드를 호출할 때는 self 인자를 전달하지 않습니다. self의 값은 인터프리터가 제공합니다.

  • 인스턴스 변수를 정의할 때에는 접두사 self.을 붙여줍니다.

initiation

image

class Car:
    color = 'red'
    category = 'sports car'

    def drive(self):
        print("I'm driving")

    def accel(self, speed_up, current_speed=10):
        self.speed_up = speed_up
        self.current_speed = current_speed + self.speed_up
        print("speed up", self.speed_up, "driving at", self.current_speed)
class Car2:
    def __init__(self, color, category):
        self.color = color
        self.category = category

    def drive(self):
        print("I'm driving")

    def accel(self, speed_up, current_speed=10):
        self.speed_up = speed_up
        self.current_speed = current_speed + self.speed_up
        print("speed up", self.speed_up, "driving at", self.current_speed)
#인스턴스 객체 선언
car1 = Car()
car2 = Car2('yellow', 'sedan')
car1.color
'red'
car2.color
'yellow'
car1.category
'sports car'
car2.category
'sedan'
class Car2:
    def __init__(self, color='red', category='sprots car'):
        self.color = color
        self.category = category

class and instance variable

class Car:
    Manufacture = "India"

    def __init__(self, color, category='sedan'):
        self.color = color
        self.category = category
car1 = Car('red','sports car')
car2 = Car('white')
print(car1.Manufacture, car1.color, car1.category)
print(car2.Manufacture, car2.color, car2.category)
India red sports car
India white sedan

encapsulation

image

class Car:
    Manufacture = "India"

    def __init__(self, color='red', category='sedan'):
        self.color = color
        self.category = category

    def drive(self):
        print("I'm driving")

    def accel(self, speed_up, current_speed=10):
        self.speed_up = speed_up
        self.current_speed = current_speed + self.speed_up
        print("speed up", self.speed_up, "driving at", self.current_speed)
class NewCar(Car):
    pass

car = NewCar()
car.drive()
car.accel(10)
I'm driving
speed up 10 driving at 20
class NewCar(Car):
    maker = 'Porsche'

car = NewCar()
car.maker
'Porsche'
class NewCar(Car):
    maker = 'Porsche'

car = NewCar()
car.maker
'Porsche'
class NewCar(Car):
    def fly(self):
        print("I'm flying!! This is the new car!!")

Method overriding

class NewCar(Car):
    def fly(self):
        print("I'm flying!! This is the new car!!")

    def drive(self):
        print("I'm driving and can fly")
class NewCar(Car):
    def __init__(self, color, category, maker):
        super().__init__(color, category)
        self.maker = maker

    def fly(self):
        print("I'm flying!! This is the new car!!")

    def accel(self, speed_up, level=1, current_speed=10):
        self.boost[level] = {1 : 0, 2 : 30, 3 : 50}
        self.speed_up = speed_up + self.boost[level]
        self.current_speed = current_speed + self.speed_up
        print("speed up", self.speed_up, "driving at", self.current_speed)
class Car:
    Manufacture = "India"

    def __init__(self, color='red', category='sedan'):
        self.color = color 
        self.category = '2020Y '+ category


class NewCar(Car):
    def __init__(self, color, category, maker):
        super().__init__(color, category)
        self.maker = maker

newcar = NewCar('red','sports car', 'Kia')
print(newcar.category)
2020Y sports car

making a n dice

  • the class name will be FunnyDice

  • input n for the instance

  • throw method will return 1~n

  • setval method will set return value to cheat

  • get current dice value

def main():
    n = get_inputs()
    mydice = FunnyDice(n)
    mydice.throw()
    print("행운의 숫자는? {}".format(mydice.getval()))
def get_inputs():
    n = int(input("주사위 면의 개수를 입력하세요: "))
    return n
class FunnyDice:
    def __init__(self, n=6):
        self.n = int(n)
        self.numbers = list(range(1, n+1))
        self.index = randrange(0, self.n)
        self.val = self.numbers[self.index]

    def throw(self):
        self.index = randrange(0, self.n)
        self.val = self.numbers[self.index]

    def getval(self):
        return self.val

    def setval(self, val):
        if val <= self.n:
            self.val = val
        else:
            msg = "주사위에 없는 숫자입니다. 주사위는 1 ~ {0}까지 있습니다. ".format(self.n)
            raise ValueError(msg)
d = FunnyDice(10)
d.throw()
print(d.getval())
9

Leave a comment