python-classes-and-objects.md

#Python Classes and Objects

Python is an object-oriented programming language. Almost everything in Python is an object, complete with its own properties and methods.

A Class acts like an object constructor, or a "blueprint" for creating objects.


#Create a Class

To create a class, use the keyword class.

Example: Create a class named MyClass with a property named x:

pythonclass MyClass:
  x = 5

#Create Object

Now we can use the class named MyClass to create objects.

Example: Create an object named p1 and print the value of x:

pythonp1 = MyClass()
print(p1.x)

#Delete Objects

You can delete objects by using the del keyword.

Example: Delete the p1 object:

pythondel p1

#Multiple Objects

You can create multiple objects from the same class.

Example: Create three objects from the MyClass class:

pythonp1 = MyClass()
p2 = MyClass()
p3 = MyClass()

print(p1.x)
print(p2.x)
print(p3.x)
Note: Each object is independent and has its own copy of the class properties.

#The pass Statement

Class definitions cannot be empty. If you have a class definition with no content for some reason, use the pass statement to avoid getting an error.

Example:

pythonclass Person:
  pass