How to define mail class and child class using python
In Python, you can define a class and its child class using inheritance. Here's an example:
# Define the parent class (Mail)
class Mail:
def __init__(self, subject, body):
self.subject = subject
self.body = body
def send(self):
print("Sending mail...")
# Define the child class (Email)
class Email(Mail):
def __init__(self, subject, body, recipient):
super().__init__(subject, body) # Call the parent class's __init__ method
self.recipient = recipient
def send(self):
print("Sending email to", self.recipient)
# Create an instance of the child class
email = Email("Hello", "This is a test email", "[email protected]")
# Call the send method on the child class instance
email.send() # Output: Sending email to [email protected]
In this example:
- The
Mail
class is the parent class, which defines the common attributes and methods for all types of mail. - The
Email
class is the child class, which inherits from theMail
class using the(Mail)
syntax. - The
Email
class overrides thesend
method to provide its own implementation, which is specific to emails. - The
Email
class also adds a new attributerecipient
that is specific to emails. - When we create an instance of the
Email
class, we can call thesend
method, which will use the overridden implementation from the child class.
Note that the super()
function is used to call the parent class's __init__
method from the child class's __init__
method. This is necessary to ensure that the parent class's attributes are initialized correctly.
You can also define multiple child classes that inherit from the same parent class, and each child class can override different methods or add new attributes specific to its own type of mail. For example:
class Letter(Mail):
def __init__(self, subject, body, sender):
super().__init__(subject, body)
self.sender = sender
def send(self):
print("Sending letter to", self.sender)
letter = Letter("Dear John", "This is a test letter", "Jane Doe")
letter.send() # Output: Sending letter to Jane Doe