Python Class and Object
In Python, a class is an abstract data type used to create objects. A class defines a data structure that contains data and functions capable of operating on that data. The data and functions within a class are referred to as the class's attributes and methods, respectively.
In Python, an object is an instance of a class. When an instance of a class is created, memory space is allocated to store the object's data. An object can access the class's attributes and methods, and it can also possess its own attributes and methods.
Here is a simple example of a class:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello, my name is {} and I'm {} years old".format(self.name, self.age))
In this example, we define a class named Person with two attributes, name and age, and one method, say_hello. The attributes name and age are initialized by the __init__ method. The __init__ method is a special method that is automatically called when an instance of the class is created. The say_hello method is used to output the person's name and age.
We can create an instance of the Person class using the following code:
person = Person("John", 30)
This creates an instance named person, where the name attribute is "John" and the age attribute is 30. We can output this person's name and age by calling the say_hello method:
person.say_hello()
This will output: Hello, my name is John and I'm 30 years old.
In Python, classes are a very powerful tool that help us organize code and create reusable code blocks. Classes can also implement more complex program logic through features such as inheritance and polymorphism.