2.introduction To Python Objects and Classes
2.introduction To Python Objects and Classes
Defining a Class
To create a class, use the `class` keyword followed by the class name.
Inside the class, you define attributes (data) and methods (functions) that the objects
of this class will have.
Example Class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return "Woof!"
Here, we've defined a class called `Dog` with attributes `name` and `age`, and a method
`bark`.
The `self` Parameter
In methods within a class, the first parameter is always `self`. It refers to the instance of the
object calling the method.It gives methods access to the object's attributes and other methods.
Creating Objects
To create an object, call the class as if it were a function, passing the required arguments to
the constructor.
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return "Woof!"
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
Conclusion
Understanding objects, classes, `self`, and constructors is crucial for organizing code
and creating efficient, modular programs in Python.
Feel free to experiment and create your own classes to model various aspects of your
projects.
Assignment #23
Question 1: Bank Account Class
Create a Python class called BankAccount that represents a simple bank account. The class
should have attributes account_number, balance, and methods deposit and withdraw. Make
sure to initialize the balance attribute using the constructor. The withdraw method should not
allow withdrawing more than the current balance.