1. Setting Up Our Robot
- Create a new class called DriveBot
- Set up a basic constructor (no parameters needed)
- Initialize three instance variables within our constructor which all default to 0: motor_speed, direction, and sensor_range
class DriveBot:
def __init__(self, motor_speed=0, sensor_range=0, direction=0):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
robot_1 = DriveBot(motor_speed=5, direction=90, sensor_range=10)
print(robot_1.motor_speed)
print(robot_1.direction)
print(robot_1.sensor_range)
or you can manually set the values like this:
class DriveBot:
def __init__(self):
self.motor_speed = 0
self.direction = 0
self.sensor_range = 0
test_bot = DriveBot()
test_bot.motor_speed = 30
test_bot.direction = 90
test_bot.sensor_range = 25
2. Adding Robot Logic
추가적으로 수정이 가능하도록 method 짜기
class DriveBot:
def __init__(self):
self.motor_speed = 0
self.direction = 0
self.sensor_range = 0
def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
3. Enhanced Constructor
parameter를 받아들이면서도 parameter가 주어지지 않으면 default값이 나오는 method 짜기
: 이 method가 1번에 처음 만들었던 method
4. Controlling Them All
- create new class variables to disable all robots and change the latitude and the longitude of all robots
class DriveBot:
all_disabled = False
latitude = -999999
longitude = -999999
#필요없는 부분 생략됨
DriveBot.all_disabled = True
DriveBot.longitude = 50.0
DriveBot.latitude = -50.0
5. Identifying Robots
- Create a new class variable in the DriveBot class called robot_count
- In the constructor, increment the robot_count by 1
- After incrementing the value, assign the value of robot_count to a new instance variable called id.
class DriveBot:
all_disabled = False
latitude = -999999
longitude = -999999
robot_count = 0
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
robot_count += 1
id = robot_count
오류
File "script.py", line 23, in <module>
robot_1 = DriveBot()
File "script.py", line 12, in __init__
robot_count += 1
UnboundLocalError: local variable 'robot_count' referenced before assignment
수정
class DriveBot:
all_disabled = False
latitude = -999999
longitude = -999999
robot_count = 0
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
DriveBot.robot_count += 1
self.id = DriveBot.robot_count
'개발일기 > PYTHON [codecademy]' 카테고리의 다른 글
Recap (Function Arguments) (0) | 2022.08.14 |
---|---|
[codecademy] 파이선 초보 단계 끝! (0) | 2022.08.13 |
[Beginner] Code Challenge: Dictionaries 2 (0) | 2022.08.13 |
[Beginner] Code Challenge: Dictionaries 1 (0) | 2022.08.13 |
[Beginner] Code Challenge: Strings (0) | 2022.08.13 |
댓글