Constructor init()
- init() is a special method that is automatically called when an object is created.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("Punitha", 22)
print(student1.name)
print(student1.age)
Output:
Punitha
22
What is self?
- self refers to the current object.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
Encapsulation
- Encapsulation means combining data and methods inside a class and controlling access to the data.
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def show_balance(self):
print(self.__balance)
account = BankAccount(5000)
account.show_balance()
Output:
5000
- self.__balance
- uses __, which is commonly used for a private member.
Top comments (0)