Python Classes and Object Creation (OOP)
Page Info
Content
Python Classes and Object Creation (OOP)
In Python, Object-Oriented Programming (OOP) allows you to create classes, which are blueprints for objects. Objects are instances of classes, containing attributes (variables) and methods (functions) that define their behavior.
Defining a Class and Creating Objects
# Define a class
class Person:
# Constructor (__init__) to initialize object attributes
def __init__(self, name, age):
self.name = name
self.age = age
# Method to display info
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Create objects (instances) of the class
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
# Access object methods
person1.greet() # Output: Hello, my name is Alice and I am 25 years old.
person2.greet() # Output: Hello, my name is Bob and I am 30 years old.
Explanation:
class Person:
Defines a class namedPerson
.__init__(self, ...)
: Constructor method that initializes object attributes.self.name
andself.age
: Instance variables unique to each object.person1 = Person("Alice", 25)
: Creates an objectperson1
of classPerson
.person1.greet()
: Calls the method defined in the class for the object.
Adding More Methods
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}.")
def have_birthday(self):
self.age += 1
print(f"Happy Birthday! {self.name} is now {self.age} years old.")
# Create an object
person = Person("Charlie", 20)
person.greet() # Output: Hello, my name is Charlie.
person.have_birthday() # Output: Happy Birthday! Charlie is now 21 years old.
Key Points
- Class: Blueprint for creating objects with attributes and methods.
- Object: Instance of a class.
- Constructor (__init__): Initializes object attributes.
- Methods: Functions defined in a class that operate on objects.
- OOP allows code reuse, modular design, and better structure in larger programs.
SEO Keywords
Python class example, Python object creation, Python OOP, Python __init__ method, Python instance methods, Python object-oriented programming
Using classes and objects in Python allows you to write modular, reusable, and organized code, which is essential for building scalable applications.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.