Python Objects and Classes
1. What is a Class and an Object
A class is a blueprint for creating objects. An object is an instance of a class.
class Person:
pass
p1 = Person()
print(p1)Classes define structure; objects represent real entities.
2. Defining a Class with Attributes
class Person:
name = "Alice"
age = 25
p = Person()
print(p.name)
print(p.age)Attributes represent properties of the class.
3. Constructor Method (__init__)
The constructor initializes object data at creation.
4. Instance Methods
Instance methods operate on object data using self.
5. Class Variables vs Instance Variables
Class variables are shared
Instance variables are unique per object
6. Creating Multiple Objects
Multiple objects can be created from the same class.
7. Modifying Object Properties
Objects allow runtime modification of attributes.
8. Deleting Object Properties and Objects
Use del to remove attributes or the object itself.
9. Built-in Object Functions
Common object-related built-ins:
type()isinstance()
10. Real-World Class Example
Encapsulation of data and behavior into a single unit.
Last updated