Object-Oriented Programming in Python Understanding Classes and Objects.
Object-Oriented Programming in Python: Understanding Classes and Objects
In Python, a class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods). Classes in Python are created by the keyword class.
An object is an instance of a class, and it has the ability to retain and manipulate its own state. In Python, you can create an object by calling the constructor of a class, which is a special method with the name init()
.
Here's an example of a simple class called Person
:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello, my name is " + self.name)
In this example, the Person class has two member variables, name
and age
, and one method say_hello()
. The init()
method is the constructor of the class, and it is called when a new object is created from the class. The self parameter is a reference to the instance of the class and is used to access the member variables and methods of the class.
To create an object from this class, you can use the following code:
p = Person("John Doe", 30)
This creates a new object p
from the Person
class, and it sets the name and age of the object to John Doe
and 30
, respectively.
To access the member variables of an object, you can use the dot notation, for example:
print(p.name) # prints "John Doe"
print(p.age) # prints 30
To call the method of an object, you can use the dot notation and parentheses, for example:
p.say_hello() # prints "Hello, my name is John Doe"
In this way, you can use classes and objects to model real-world objects and their behavior in your Python programs, and make your code more organized and efficient.