0305 FreeCodeCamp Python Certification — Classes and Objects Review
Classes and Objects Review**
Python Classes and Objects
- Class Definition: A class is a blueprint for creating objects. It defines the behavior an object will have through its attributes and methods.
class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print(f'{self.name.upper()} says woof woof!') - Creating Objects: Objects are instances of a class. They are created by calling the class with the necessary arguments.
dog1 = Dog('Jack', 3) dog2 = Dog('Thatcher', 5) dog1.bark() # JACK says woof woof! dog2.bark() # THATCHER says woof woof! - Calling Methods on Objects: You can call methods on objects to perform actions or retrieve information.
object_name1.method_name() object_name2.method_name() - Difference Between Class and Object: A class is a reusable template, while an object is a specific instance of that class with actual data.
Attributes
- Instance Attributes: Defined in
__init__()usingself, and unique to each object. - Class Attributes: Defined directly inside the class and shared by all instances.
Methods
- Methods: Functions defined inside a class that operate on the object’s attributes.
- Accessing Methods: Call methods on objects using the dot notation.