library(reticulate)
py_install("matplotlib")
Using virtual environment "~/.virtualenvs/r-reticulate" ...
#py_install("pandas")
#py_install("numpy")
#use_virtualenv("r-reticulate")
#plt <- import("matplotlib.pyplot")
Python is an object-oriented programming (OOP) language that uses a paradigm centered around objects and classes.
Using virtual environment "~/.virtualenvs/r-reticulate" ...
A class is a blueprint or template for creating objects. It defines the structure and behavior that its objects will have.
class
keyword.nameofclass
is the class we are declaring/creatingclass_attribute = value
class_attr_value = ClassName.class_attribute
accesses the class attribute class_attribute
from the ClassName class
and assigns its value to the variable.class_attr_value
.When you create a class, you specify the attributes
(data) and methods
(functions) that objects of that class will have.
Attributes
are defined as variables within the class, andmethods
are defined as functions.class
withattributes
such as “color” and “speed,” along withmethods
like “accelerate.”def __init __(self, attribute1, attribute2, …):
__init__
method is a special method known as the constructor.self
parameter is the first parameter of the constructor, referring to the instance being created: the newly created instance of the classself.attribute1
, self.attribute2
, and so on are used to assign values to instance attributes.class nameofclass:
# Attributes are shared by all instances (objects)
class_attribute = value
# Constructor method (initialize instance attributes)
def __init__(self, attribute1, attribute2, ...):
self.attribute1 = attribute1
self.attribute2 = attribute2
# ...
# Instance methods (functions)
def method1(self, parameter1, parameter2, ...):
# Method logic
pass
def method2(self, parameter1, parameter2, ...):
# Method logic
pass
__init__
method using the self keyword followed by the attribute name.An object is a fundamental unit in Python that represents a real-world entity or concept. Objects can be tangible (like a car) or abstract (like a student’s grade).
Every object has two main characteristics:
The attributes or data that describe the object.
The actions or methods that the object can perform.
Once you’ve defined a class, you can create individual objects (instances) based on that class.
Each object is independent and has its own set of attributes and methods.
To create objects (instances) of the class, you call the class like a function and provide arguments the constructor requires.
Each object is a distinct instance of the class, with its own instance attributes and the ability to call methods defined in the class.
so: “my_car = Car()” as a full example look below:
object1
& object2
method1
and method2
were defined in nameofclass classparam1_value
and param2_value
as arguments to these methodsmethod_reference = object1.method1
assigns the method method1 of object1 to the variable method_reference.attribute_value = object1.attribute1
retrieves the value of the attribute attribute1 from object1 and assigns it to the variable attribute_value.object1.attribute2 = new_value
sets the attribute attribute2 of object1 to the new value new_value.Let’s start by defining a Car
class that includes the following attributes and methods:
max_speed
, which is set to 120 km/h.__init__
that takes parameters for the car’s make, model, color, and an optional speed (defaulting to 0). This method initializes instance attributes for make, model, color, and speed.accelerate(self, acceleration)
that allows the car to accelerate. If the acceleration does not exceed the max_speed
, update the car’s speed attribute. Otherwise, set the speed to the max_speed.get_speed(self)
that returns the current speed of the car.class Car:
# Class attribute (shared by all instances)
max_speed = 120 # Maximum speed in km/h
# Constructor method (initialize instance attributes)
def __init__(self, make, model, color, speed=0):
self.make = make
self.model = model
self.color = color
self.speed = speed # Initial speed is set to 0
# Method for accelerating the car
def accelerate(self, acceleration):
if self.speed + acceleration <= Car.max_speed:
self.speed += acceleration
else:
self.speed = Car.max_speed
# Method to get the current speed of the car
def get_speed(self):
return self.speed
Now, we will instantiate two objects of the Car
class, each with the following characteristics:
Using the accelerate
method, increase the speed of car1 by 30 km/h and car2 by 20 km/h
Display the current speed of each car using the get_speed
method
# Print the current speeds of the cars
print(f"{car1.make} {car1.model} color: {car1.color} is currently at {car1.get_speed()} km/h.")
Toyota Camry color: Blue is currently at 30 km/h.
Honda Civic color: Red is currently at 20 km/h.
Note:
car1.make
or car2.model
car1.make = "Buick"
will change car1.make
valueget_speed
method we can acquire the speed by calling the .speed
to retrieve the speed attributeWe will create two classes: Circle and Rectangle
__init__
, which is used to initialize the object.self
contains all the attributes in the set. For example the self.color
gives the value of the attribute color and self.radius
will give you the radius of the object.add_radius()
with the parameter r
, the method adds the value of r
to the attribute radius.self.radius
. # Create a class Circle
class Circle(object):
# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
# Method
def add_radius(self, r):
self.radius = self.radius + r
return(self.radius)
# Method
def drawCircle(self):
plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))
plt.axis('scaled')
plt.show()
Circle
class and pass it two parameters: radius and colordir()
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add_radius', 'color', 'drawCircle', 'radius']
add_radius
we can call it to change the radiusRadius of object: 1
3
Radius of object of after applying the method add_radius(2): 3
8
Radius of object of after applying the method add_radius(5): 8
# Create a new Rectangle class for creating a rectangle object
class Rectangle(object):
# Constructor
def __init__(self, width=2, height=3, color='r'):
self.height = height
self.width = width
self.color = color
# Method
def drawRectangle(self):
plt.gca().add_patch(plt.Rectangle((0, 0), self.width, self.height ,fc=self.color))
plt.axis('scaled')
plt.show()