8. Basic Object-Oriented Python (127m) Flashcards
What is Object Oriented Programming in Python? What is Properties and Behaviours?
Object-oriented programming (OOP) is a programming paradigm that organizes code into objects, which are instances of classes. Python is an object-oriented programming language that supports the creation and manipulation of objects.
In OOP, objects are the building blocks that encapsulate data (properties) and behavior (methods or functions) together. Let’s delve deeper into properties and behaviors:
- Properties: Properties represent the data or attributes associated with an object. They define the state of an object and store information. In Python, properties are typically represented by variables or attributes within a class. Each object of a class has its own set of property values.
For example, consider a class named “Car.” The properties of a car object might include its color, brand, and model. These properties can be defined as variables within the class:
```python
class Car:
def __init__(self, color, brand, model):
self.color = color
self.brand = brand
self.model = model
~~~
Here, color
, brand
, and model
are properties of the car object. You can create instances of the class and assign specific values to these properties:
```python
my_car = Car(“red”, “Toyota”, “Camry”)
print(my_car.color) # Output: red
~~~
- Behaviors: Behaviors represent the actions or operations that an object can perform. They define how an object can interact with other objects or manipulate its own state. In Python, behaviors are typically implemented as methods or functions within a class.
Continuing with our “Car” example, let’s define a behavior for the car object, such as starting the engine:
```python
class Car:
def __init__(self, color, brand, model):
self.color = color
self.brand = brand
self.model = model
def start_engine(self): print("Engine started!") ~~~
The start_engine
method allows the car object to perform the action of starting the engine. You can call this method on an instance of the class:
```python
my_car = Car(“red”, “Toyota”, “Camry”)
my_car.start_engine() # Output: Engine started!
~~~
In this case, start_engine()
is the behavior associated with the car object. Different objects of the same class can invoke their own behaviors while maintaining their individual property values.
Object-oriented programming provides a powerful way to model real-world concepts, allowing you to define and manipulate objects with their own properties and behaviors.
What is OOP?
Vocab:
* OOP = Object-Oriented Programming
* Object-Oriented Programming = a way of structuring your code into groups of properties and behaviors
Example Object: Car
Properties:
* 4 wheels
* 2 doors
* Make
* Model
* Year
Behaviors:
* Stop
* Go
* Turn
Python objects
Here are the Python docs about each of these objects. It’s a good habit to check out the documentation and start getting used to reading about how things work.
* List
* String
* Dictionary
* Tuple
Things I’ve interacted with today:
Dog
* Properties: 2 eyes, 2 ears, tail
* Behaviors: fetch, bark, whine, wag tail
Oven
* Properties: buttons, door, racks, light
* Behaviors: heating, timer, light on/off
What is a class and how to write it in Python?
In Python, a class is a blueprint for creating objects. It serves as a template that defines the properties (attributes) and behaviors (methods) that objects of that class will have. The class specifies the common characteristics and functionalities shared by its instances (objects).
To define a class in Python, you use the class
keyword followed by the class name. Here’s a basic syntax for creating a class:
```python
class ClassName:
# class variables and methods go here
~~~
Inside the class, you can define various elements, including:
- Constructor Method: The constructor method
\_\_init\_\_()
is called when an object of the class is instantiated. It is used to initialize the object’s properties. It must haveself
as the first parameter, which refers to the object itself.
```python
class ClassName:
def __init__(self, parameter1, parameter2, …):
# initialize properties here
self.property1 = parameter1
self.property2 = parameter2
~~~
- Instance Methods: Instance methods are functions defined within the class that can be invoked on objects of the class. They can access and manipulate the object’s properties using the
self
parameter.
```python
class ClassName:
def __init__(self, parameter1, parameter2, …):
self.property1 = parameter1
self.property2 = parameter2
def method1(self, parameter1, parameter2, ...): # method code goes here ~~~
- Class Variables: Class variables are shared among all instances of the class. They are defined within the class but outside any method. They can be accessed using the class name or any instance of the class.
```python
class ClassName:
class_variable = value
def \_\_init\_\_(self, parameter1, parameter2, ...): self.property1 = parameter1 self.property2 = parameter2 ~~~
Here’s an example that puts it all together:
```python
class Car:
wheels = 4 # class variable
def \_\_init\_\_(self, color, brand, model): self.color = color self.brand = brand self.model = model def start_engine(self): print("Engine started!") def drive(self, distance): print(f"The {self.color} {self.brand} {self.model} is driving {distance} miles.") ~~~
You can create instances of the class using the class name followed by parentheses, passing the required arguments to the constructor:
```python
my_car = Car(“red”, “Toyota”, “Camry”)
~~~
You can then access the object’s properties and invoke its methods:
```python
print(my_car.color) # Output: red
my_car.start_engine() # Output: Engine started!
my_car.drive(100) # Output: The red Toyota Camry is driving 100 miles.
~~~
This is a basic overview of defining a class in Python. Classes provide a way to create reusable and organized code, allowing you to model complex systems and create objects with specific behaviors and attributes.
Explain the following code:
class Car(): pass my_car = Car() print(my_car) print(type(my_car)) print(isinstance(my_car, Car))
What output will it give?
The code snippet you provided creates a class called Car
and then creates an instance of that class named my_car
. It then prints the object, its type, and checks whether the object is an instance of the Car
class using the isinstance()
function. Let’s break down the code and examine the output it will produce:
```python
class Car():
pass
~~~
In this line, a class named Car
is defined using the class
keyword. The pass
statement acts as a placeholder, indicating that the class body is empty. This means the Car
class doesn’t have any specific properties or methods defined.
```python
my_car = Car()
~~~
Here, an instance of the Car
class is created using the class name followed by parentheses. The parentheses ()
indicate the invocation of the class constructor or initializer method, \_\_init\_\_()
. Since the class body is empty, this instance won’t have any specific properties or behaviors.
```python
print(my_car)
~~~
This line prints the value of the my_car
object. However, since the Car
class doesn’t have any specific implementation or string representation defined, the output will be something like <\_\_main\_\_.Car object at 0x...>
. The specific memory address (0x...
) may vary.
```python
print(type(my_car))
~~~
This line prints the type of the my_car
object using the type()
function. It will output <class '\_\_main\_\_.Car'>
, indicating that my_car
is an object of the Car
class defined in the current module (\_\_main\_\_
).
```python
print(isinstance(my_car, Car))
~~~
This line checks whether my_car
is an instance of the Car
class using the isinstance()
function. It will return True
if my_car
is an instance of the Car
class, and False
otherwise. Since my_car
is indeed created using the Car
class, the output will be True
.
So, overall, the code will produce the following output:
<\_\_main\_\_.Car object at 0x...> <class '\_\_main\_\_.Car'> True
The specific memory address (0x...
) and representation may vary, but the output confirms that my_car
is an object of the Car
class and is indeed an instance of the Car
class.
What does print(), type(), isinstance() do in classes and how can it help me identify classes?
In Python, the print()
, type()
, and isinstance()
functions are commonly used tools to work with classes and objects. Here’s an explanation of what each of these functions does and how they can help you identify classes and objects:
-
print()
: Theprint()
function is used to display output on the console. When applied to an object, it calls the object’s\_\_str\_\_()
method to get a string representation of the object, which is then printed. It helps you examine the value or representation of an object, such as its properties or other relevant information. -
type()
: Thetype()
function is used to determine the type of an object. When passed an object as an argument, it returns the type or class of that object. It helps you identify the class to which an object belongs. -
isinstance()
: Theisinstance()
function is used to check whether an object is an instance of a particular class. It takes two arguments: the object you want to check and the class you want to compare it against. It returnsTrue
if the object is an instance of the class, andFalse
otherwise. It helps you verify the relationship between an object and a class.
These functions are often used during development and debugging to inspect objects and verify their types. They can be helpful in the following scenarios:
- Identifying the class of an object: You can use
type()
to determine the class of an object. This is particularly useful if you have multiple classes and want to confirm which class an object belongs to. - Verifying inheritance or class relationships:
isinstance()
can be used to check if an object is an instance of a specific class or any of its derived classes. This helps in understanding the inheritance hierarchy and confirming relationships between classes. - Debugging and troubleshooting: By printing the object using
print()
, you can examine its properties, values, or other relevant information to understand its current state and aid in debugging your code.
Overall, these functions are valuable tools for inspecting and understanding classes and objects during development, allowing you to identify classes, verify relationships, and gain insights into object properties.
When creating a blueprint for an object, you use the ` ______ `keyword. Fill in the blanks.
When creating a blueprint for an object, you use the class
keyword.
Explain the following code:
class Car(): wheels = 4 doors = 2 engine = True car_one = Car() car_two = Car() car_two.doors = 6 Car.doors = 4 print(f'Car One: {car_one.doors}') print(id(car_one.doors)) print(f'Car Two: {car_two.doors}') print(id(car_two.doors)) print(f'Car Global: {Car.doors}') print(id(Car.doors))
What output will it give and also explain ID and will ID change if following change is made to the code Car.doors = 5.
The given code defines a Car
class with some class-level attributes and creates two instances of the Car
class. Here’s a breakdown of the code and its output:
```python
class Car():
wheels = 4
doors = 2
engine = True
~~~
In this section, a Car
class is defined with three class-level attributes: wheels
, doors
, and engine
. These attributes define the characteristics of a car and are shared among all instances of the Car
class.
```python
car_one = Car()
car_two = Car()
~~~
Two instances of the Car
class, car_one
and car_two
, are created using the class constructor. Both instances will have the same initial attribute values inherited from the class.
```python
car_two.doors = 6
Car.doors = 4
~~~
The attribute doors
of car_two
is modified directly, changing its value to 6. This modification affects only the doors
attribute of car_two
and doesn’t change the class-level attribute or affect other instances.
The class-level attribute doors
is also modified by directly accessing it via the Car
class itself. The value is changed to 4, and this change affects all instances of the Car
class.
```python
print(f’Car One: {car_one.doors}’)
print(id(car_one.doors))
print(f’Car Two: {car_two.doors}’)
print(id(car_two.doors))
print(f’Car Global: {Car.doors}’)
print(id(Car.doors))
~~~
The print
statements in this section output the values of doors
for car_one
, car_two
, and the class Car
itself. The id()
function is used to retrieve the unique identifier of the object referenced by the attribute.
Output:
~~~
Car One: 2
<id1>
Car Two: 6
<id2>
Car Global: 4
<id3>
~~~
Explanation of the output:
- `Car One: 2`: The value of `doors` for `car_one` is 2, which is the initial value inherited from the class. This value hasn't been modified for `car_one`.
- `<id1>`: The unique identifier (memory address) of the object referenced by `car_one.doors`.
- `Car Two: 6`: The value of `doors` for `car_two` is 6, which was directly modified for this instance.
- `<id2>`: The unique identifier (memory address) of the object referenced by `car_two.doors`.
- `Car Global: 4`: The value of the class-level attribute `doors` after it was modified using `Car.doors = 4`.
- `<id3>`: The unique identifier (memory address) of the object referenced by `Car.doors`.
Regarding the question about the `id` changing if `Car.doors = 5` is made:
If you change `Car.doors = 5` before the print statements, the output will be:
~~~
Car One: 2
<id1>
Car Two: 6
<id2>
Car Global: 5
<id4>
~~~
The `id` of `car_one.doors` and `car_two.doors` will remain the same since their values haven't changed. However, the `id` of `Car.doors` will change because the value of the class-level attribute has changed, resulting in a new object being created with the value 5.
</id4></id2></id1></id3></id2></id1></id3></id2></id1>
What is instance attribute in Python?
In Python, an instance attribute is a variable that belongs to a specific instance of a class. It is defined within the methods of the class and is accessed using the instance of the class. Each instance of the class has its own copy of the instance attributes.
Instance attributes are used to store data that is unique to each instance of a class. They can have different values for different instances of the same class. Instance attributes define the state of an object and can be accessed and modified using the dot notation.
Here’s an example to illustrate instance attributes in Python:
```python
class Car:
def __init__(self, brand, model):
self.brand = brand # instance attribute
self.model = model # instance attribute
def display_info(self): print(f"Brand: {self.brand}, Model: {self.model}")
car1 = Car(“Toyota”, “Camry”)
car2 = Car(“Honda”, “Civic”)
car1.display_info() # Output: Brand: Toyota, Model: Camry
car2.display_info() # Output: Brand: Honda, Model: Civic
~~~
In the example above, the brand
and model
variables are instance attributes of the Car
class. Each instance of the Car
class (car1
and car2
) has its own copy of these attributes, which can be accessed using self.brand
and self.model
respectively.
TeamTreeHouse Notes:
* Attributes = the name in Python for the properties of an object
* Instance attributes = attributes that are created when an object is instantiated
* Method = a function inside of a class
* Dunder method = a nickname for a method that has double underscores before and after its name (Ex: __init__)
what is \_\_init\_\_
in python?
In Python, \_\_init\_\_
is a special method, also known as the constructor, that is automatically called when an object of a class is created. It is used to initialize the attributes of the object and perform any other setup or initialization tasks.
The \_\_init\_\_
method is defined within a class and takes the self
parameter, which represents the instance of the class being created. It can also take additional parameters that are used to initialize the attributes of the object.
Here’s an example to illustrate the usage of \_\_init\_\_
:
```python
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self): print(f"Brand: {self.brand}, Model: {self.model}")
car1 = Car(“Toyota”, “Camry”)
car1.display_info() # Output: Brand: Toyota, Model: Camry
~~~
In the example above, the Car
class has an \_\_init\_\_
method that takes brand
and model
as parameters. Inside the \_\_init\_\_
method, the attributes self.brand
and self.model
are initialized with the values passed to the constructor.
When car1 = Car("Toyota", "Camry")
is executed, the \_\_init\_\_
method is automatically called with self
set to car1
, and the attributes brand
and model
are set to “Toyota” and “Camry” respectively.
The \_\_init\_\_
method allows you to set up the initial state of an object and perform any necessary initialization tasks before using the object further. It is a common practice to define the \_\_init\_\_
method in Python classes to ensure that objects are properly initialized when created.
What is \_\_init\_\_
in python?
In Python, \_\_init\_\_
is a special method, also known as the constructor, that is automatically called when an object of a class is created. It is used to initialize the attributes of the object and perform any other setup or initialization tasks.
The \_\_init\_\_
method is defined within a class and takes the self
parameter, which represents the instance of the class being created. It can also take additional parameters that are used to initialize the attributes of the object.
Here’s an example to illustrate the usage of \_\_init\_\_
:
```python
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self): print(f"Brand: {self.brand}, Model: {self.model}")
car1 = Car(“Toyota”, “Camry”)
car1.display_info() # Output: Brand: Toyota, Model: Camry
~~~
In the example above, the Car
class has an \_\_init\_\_
method that takes brand
and model
as parameters. Inside the \_\_init\_\_
method, the attributes self.brand
and self.model
are initialized with the values passed to the constructor.
When car1 = Car("Toyota", "Camry")
is executed, the \_\_init\_\_
method is automatically called with self
set to car1
, and the attributes brand
and model
are set to “Toyota” and “Camry” respectively.
The \_\_init\_\_
method allows you to set up the initial state of an object and perform any necessary initialization tasks before using the object further. It is a common practice to define the \_\_init\_\_
method in Python classes to ensure that objects are properly initialized when created.
What is Dunder Init?
“Dunder init” is a shorthand term for the special method \_\_init\_\_
in Python. “Dunder” is derived from “double underscore,” which is represented by the character \_\_
surrounding the method name.
The \_\_init\_\_
method is a special method in Python classes that serves as the constructor. It is automatically called when an object of a class is created, allowing you to initialize the object’s attributes and perform any necessary setup or initialization tasks.
Here’s an example to demonstrate the usage of \_\_init\_\_
(dunder init):
```python
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self): print(f"Brand: {self.brand}, Model: {self.model}")
car1 = Car(“Toyota”, “Camry”)
car1.display_info() # Output: Brand: Toyota, Model: Camry
~~~
In the example above, \_\_init\_\_
is the dunder init method of the Car
class. It takes self
(representing the instance of the class) as the first parameter, followed by any additional parameters (brand
and model
in this case).
When car1 = Car("Toyota", "Camry")
is executed, the dunder init method \_\_init\_\_
is automatically called with self
set to car1
and brand
and model
set to “Toyota” and “Camry” respectively. Inside the \_\_init\_\_
method, the attributes self.brand
and self.model
are initialized with these values.
Using dunder methods like \_\_init\_\_
allows you to define the behavior of your objects at specific moments or when certain operations are performed. They provide a way to customize the behavior of Python classes to suit your needs.
Explain the following codes:
One is:
~~~
class Pet():
legs: 4
ears: 2
tail: 1
def \_\_init\_\_(self, kind, breed, age): self.kind = kind self.breed = breed self.age = age
pet_1 = Pet(‘cat’, ‘indian’, 2)
pet_2 = Pet(‘dog’, ‘german’, 1)
print(f’Pet 1 is a {pet_1.kind} of {pet_1.breed} breed and is {pet_1.age} years old’)
print(f’Pet 2 is a {pet_2.kind} of {pet_2.breed} breed and is {pet_2.age} years old’)
~~~
And Two is:
~~~
class Car():
wheels = 4
doors = 2
engine = True
def \_\_init\_\_(self, model, year, make='VW Group'): self.make = make self.model = model self.year = year
car_one = Car(‘Vento’, 2014)
car_two = Car(‘A4’, 2024, ‘Audii’)
print(f’Car One: {car_one.doors}’)
print(id(car_one.doors))
print(f’Car Two: {car_two.doors}’)
print(id(car_two.doors))
print(f’Car Global: {Car.doors}’)
print(id(Car.doors))
print(f’The car one is {car_one.make} {car_one.model} {car_one.year}’)
print(f’The car two is {car_two.make} {car_two.model} {car_two.year}’)
~~~
Sure! Let’s go through each code snippet and explain what it does.
Code Snippet One:
```python
class Pet():
legs: 4
ears: 2
tail: 1
def \_\_init\_\_(self, kind, breed, age): self.kind = kind self.breed = breed self.age = age
pet_1 = Pet(‘cat’, ‘indian’, 2)
pet_2 = Pet(‘dog’, ‘german’, 1)
print(f’Pet 1 is a {pet_1.kind} of {pet_1.breed} breed and is {pet_1.age} years old’)
print(f’Pet 2 is a {pet_2.kind} of {pet_2.breed} breed and is {pet_2.age} years old’)
~~~
Explanation:
1. The code defines a class named Pet
.
2. Inside the class, there are class attributes legs
, ears
, and tail
which are set to the specified values. These attributes are shared among all instances of the class.
3. The \_\_init\_\_
method is defined as the constructor. It takes parameters kind
, breed
, and age
, and initializes instance attributes self.kind
, self.breed
, and self.age
with the passed values.
4. Two instances of the Pet
class, pet_1
and pet_2
, are created using different arguments.
5. The print
statements display information about the pets, accessing their attributes using dot notation (pet_1.kind
, pet_1.breed
, pet_1.age
, etc.).
Output:
~~~
Pet 1 is a cat of indian breed and is 2 years old
Pet 2 is a dog of german breed and is 1 years old
~~~
Code Snippet Two:
```python
class Car():
wheels = 4
doors = 2
engine = True
def \_\_init\_\_(self, model, year, make='VW Group'): self.make = make self.model = model self.year = year
car_one = Car(‘Vento’, 2014)
car_two = Car(‘A4’, 2024, ‘Audii’)
print(f’Car One: {car_one.doors}’)
print(id(car_one.doors))
print(f’Car Two: {car_two.doors}’)
print(id(car_two.doors))
print(f’Car Global: {Car.doors}’)
print(id(Car.doors))
print(f’The car one is {car_one.make} {car_one.model} {car_one.year}’)
print(f’The car two is {car_two.make} {car_two.model} {car_two.year}’)
~~~
Explanation:
1. The code defines a class named Car
.
2. Inside the class, there are class attributes wheels
, doors
, and engine
which are set to the specified values. These attributes are shared among all instances of the class.
3. The \_\_init\_\_
method is defined as the constructor. It takes parameters model
, year
, and an optional parameter make
with a default value of 'VW Group'
. It initializes instance attributes self.make
, self.model
, and self.year
with the passed values.
4. Two instances of the Car
class, car_one
and car_two
, are created using different arguments.
5. The print
statements display information about the cars, accessing their attributes using dot notation (car_one.doors
, car_one.make
, etc.).
6. The id()
function is used to display the
memory address of the doors
attribute, demonstrating that it refers to the same object across instances and the class.
Output:
~~~
Car One: 2
<id1>
Car Two: 2
<id1>
Car Global: 2
<id1>
The car one is VW Group Vento 2014
The car two is Audii A4 2024
~~~
Note: The `<id1>` placeholder represents the memory address of the `doors` attribute, which will be different each time the code is executed.
</id1></id1></id1></id1>
Challenge 1: Create a class called Panda. Inside your class, create two class attributes. One called species set to ‘Ailuropoda melanoleuca’ and another called food set to ‘bamboo’.
Challenge 2: Add an __init__ method to your class. It should only take the self argument. Inside the method, create an instance attribute called is_hungry and set it equal to True.
Challenge 1: Creating the Panda class with class attributes.
```python
class Panda:
species = ‘Ailuropoda melanoleuca’
food = ‘bamboo’
~~~
In the above code, we define a class called Panda
. Inside the class, we create two class attributes: species
set to the string 'Ailuropoda melanoleuca'
and food
set to the string 'bamboo'
.
Challenge 2: Adding the __init__ method and instance attribute.
```python
class Panda:
species = ‘Ailuropoda melanoleuca’
food = ‘bamboo’
def \_\_init\_\_(self): self.is_hungry = True ~~~
In the updated code, we add the \_\_init\_\_
method to the Panda
class. The \_\_init\_\_
method takes only the self
argument, as it is always required in a method within a class. Inside the \_\_init\_\_
method, we create an instance attribute called is_hungry
and set it to True
.
Now, when you create an instance of the Panda
class, the is_hungry
attribute will be automatically initialized to True
.
Here’s an example usage:
```python
panda = Panda()
print(panda.species) # Output: Ailuropoda melanoleuca
print(panda.food) # Output: bamboo
print(panda.is_hungry) # Output: True
~~~
In the example above, we create an instance of the Panda
class called panda
. We can access the class attributes species
and food
using the instance (panda.species
and panda.food
) and the instance attribute is_hungry
(panda.is_hungry
).
Explain the following code:
class Car(): wheels = 4 doors = 2 engine = True def \_\_init\_\_(self, model, year, make='VW Group'): self.make = make self.model = model self.year = year self.gas = 100 self.is_moving = False def stop(self): if self.is_moving: print("The Car has Stopped!") self.is_moving = False else: print("The Car has already Stopped!!") def go(self, speed): if self.use_gas(): if not self.is_moving: print("The Car starts is Moving") self.is_moving = True print(f'The car is going at {speed}') else: print("You have run out of gas") self.stop() def use_gas(self): self.gas -= 50 if self.gas <= 0: return False else: return True car_one = Car('Vento', 2014) car_two = Car('A4', 2024, 'Audii') car_one.stop() car_one.go(120) car_one.go('fast') car_one.stop() car_one.stop() car_one.go(100)
The code provided defines a class Car
and demonstrates its usage. Let’s go through the code and explain its functionality step by step:
```python
class Car():
wheels = 4
doors = 2
engine = True
def \_\_init\_\_(self, model, year, make='VW Group'): self.make = make self.model = model self.year = year self.gas = 100 self.is_moving = False ~~~
- The code defines a class named
Car
. - Inside the class, there are class attributes
wheels
,doors
, andengine
which are set to their respective values. These attributes are shared among all instances of the class. - The
\_\_init\_\_
method is defined as the constructor. It takes parametersmodel
,year
, and an optional parametermake
with a default value of'VW Group'
. - Inside the
\_\_init\_\_
method, there are instance attributesself.make
,self.model
,self.year
,self.gas
, andself.is_moving
. These attributes store specific data for each instance of the class.
```python
def stop(self):
if self.is_moving:
print(“The Car has Stopped!”)
self.is_moving = False
else:
print(“The Car has already Stopped!!”)
~~~
- The
stop
method is defined within theCar
class. - It checks the
is_moving
attribute of the instance to determine if the car is already moving. - If the car is moving (
self.is_moving
isTrue
), it prints a message indicating that the car has stopped and updatesself.is_moving
toFalse
. - If the car is not moving (
self.is_moving
isFalse
), it prints a message indicating that the car has already stopped.
```python
def go(self, speed):
if self.use_gas():
if not self.is_moving:
print(“The Car starts is Moving”)
self.is_moving = True
print(f’The car is going at {speed}’)
else:
print(“You have run out of gas”)
self.stop()
~~~
- The
go
method is defined within theCar
class. - It first checks if there is enough gas by calling the
use_gas
method. - If there is enough gas (
self.use_gas()
returnsTrue
), it checks if the car is not already moving (self.is_moving
isFalse
). - If the car is not moving, it prints a message indicating that the car has started moving and updates
self.is_moving
toTrue
. - It then prints a message indicating the speed at which the car is going, using the
speed
parameter passed to the method. - If there is not enough gas (
self.use_gas()
returnsFalse
), it prints a message indicating that the car has run out of gas and calls thestop
method to stop the car.
```python
def use_gas(self):
self.gas -= 50
if self.gas <= 0:
return False
else:
return True
~~~
- The
use_gas
method is defined within theCar
class. - It subtracts 50 from the
self.gas
attribute to simulate gas consumption. - It then checks if the gas level is below or equal to 0. If it is, it returns
False
to indicate that there is not enough gas. - Otherwise
, if the gas level is above 0, it returns True
to indicate that there is enough gas.
```python
car_one = Car(‘Vento’, 2014)
car_two = Car(‘A4’, 2024, ‘Audii’)
car_one.stop()
car_one.go(120)
car_one.go(‘fast’)
car_one.stop()
car_one.stop()
car_one.go(100)
~~~
- Two instances of the
Car
class,car_one
andcar_two
, are created with different arguments passed to the constructor. - Method calls are made on the
car_one
instance to stop the car (car_one.stop()
), go at a speed of 120 (car_one.go(120)
), go at a speed of ‘fast’ (car_one.go('fast')
), stop the car again (car_one.stop()
), stop the car again (car_one.stop()
), and finally go at a speed of 100 (car_one.go(100)
).
The code demonstrates the usage of class attributes, instance attributes, methods, and instance initialization. It simulates the behavior of a car object, such as starting, stopping, and consuming gas.
Challenge 1: Using your Panda class, add two arguments to your class in the __init__ method called name and age. Set the values inside of the __init__ method using self.
class Panda: species = 'Ailuropoda melanoleuca' food = 'bamboo' def \_\_init\_\_(self): self.is_hungry = True
Challenge 2:
Create a method called eat. It should only take self as an argument. Inside of the method, set the is_hungry attribute to False, since the Panda will no longer be hungry when it eats. Also, return a string that says ‘Bao Bao eats bamboo.’ where ‘Bao Bao’ is the name attribute and ‘bamboo’ is the food attribute.
Challenge 3:
Create another method called check_if_hungry that also only takes self. Inside of the method, if the is_hungry attribute is True, then call the eat method.
Certainly! Here’s the modified code that addresses all three challenges:
```python
class Panda:
species = ‘Ailuropoda melanoleuca’
food = ‘bamboo’
def \_\_init\_\_(self, name, age): self.name = name self.age = age self.is_hungry = True def eat(self): self.is_hungry = False return f'{self.name} eats {self.food}.' def check_if_hungry(self): if self.is_hungry: self.eat()
panda = Panda(‘Bao Bao’, 5)
print(panda.check_if_hungry())
~~~
In the modified code:
Challenge 1: The \_\_init\_\_
method of the Panda
class now accepts name
and age
as arguments and initializes the instance attributes self.name
, self.age
, and self.is_hungry
with the respective values.
Challenge 2: The eat
method sets self.is_hungry
to False
to indicate that the panda is no longer hungry. It returns a string using the instance attribute self.name
and the class attribute self.food
.
Challenge 3: The check_if_hungry
method checks if the panda is hungry (self.is_hungry
is True
). If so, it calls the eat
method to feed the panda.
The example usage prints the result of calling the check_if_hungry
method on the panda
instance.
Output:
~~~
Bao Bao eats bamboo.
~~~
Now, the code correctly initializes the name
and age
attributes, allows the panda to eat, and checks if it is hungry before feeding it.