Lecture_2#_Classes_and_Objects (1)
Lecture_2#_Classes_and_Objects (1)
Using
Python
Teemu Matilainen
teemu.matilainen@savonia.fi
Lecture 2#
A class is a blueprint or a template (abstract: dog) for creating objects. It defines a set
of attributes (data) and methods (functions) that the objects of the class will have. In
Python, a class is created using the class keyword.
Simple class:
Now we create a simple skeleton of a class. Class does not do anything… yet.
Now, consider a program in which two variables, 'name' and 'age,' are
added to a Simple_class object. Any variables associated with an
object are referred to as its attributes, specifically, data attributes or,
at times, instance variables.
Output:
In this
example:
• Dog is a class with
attributes name and
age, and a method bark.
• The init method is
a special method called
the constructor, which
initializes the object's
attributes when an
instance is created.
• my_dog is an instance
(object) of the Dog class.
Exercise:
Output
Objects:
An object is an instance of a class. It is a concrete realization of the class, with its own
unique state (attribute values). Objects can perform actions (methods) defined by the
class. In the example above, my_dog is an object of the Dog class.
In Python, an object is an instance of a class, and a class is a blueprint for creating
objects. Objects can have associated methods, which are functions that are defined
within the class and can operate on the object's attributes.
Methods are essentially functions that are bound to the object and can access and
modify its state.
Instantiation:
The process of creating an object from a class is called instantiation. In the example,
my_dog = Dog(name=’Nino', age=3) is an instantiation of the Dog class.
Encapsulation:
Encapsulation is the bundling of data and methods that operate on the data within a single unit,
i.e., a class. The attributes and methods of a class are encapsulated within that class, providing
a way to control access and modification.
Inheritance:
Inheritance is a mechanism where a new class (subclass or derived class) can inherit attributes
and methods from an existing class (base class or parent class). It promotes code reuse and
extensibility.
Polymorphism:
Polymorphism allows objects of different classes to be treated as objects of a common base
class. It enables flexibility and extensibility in code.
These concepts collectively form the foundation of object-oriented programming and are
widely used in Python and many other programming languages.
• Compile-Time Polymorphism
(Static Binding):
• Here is partially
created shopping list
class. Fill the gaps…