-3

Please allow me to illustrate my question with a simple example. Let's suppose we have a Customer class:

class Customer:
def __init__(self, name, surname, email):
    self.name = name
    self.surname = surname
    self.email = email

And we also have a Bill class that needs info from a Customer object instance. Should I write the Bill by providing a Customer object instance as an argument?

class Bill:
def __init__(self, amount, customer):
    self.amount = amount
    self.customer = customer

def to_txt(self):
    with open("bill.txt", "w") as file:
        file.write(f"{self.customer.name} due amount is {self.amount}")

customer = Customer("John", "Smith", "[email protected]") bill = Bill(100, customer)

Or should Bill simply get a name as an argument as shown below?

class Bill:
def __init__(self, amount, period, customer):
    self.amount = amount
    self.period = period
    self.customer_name = customer_name

def to_txt(self):
    with open("bill.txt", "w") as file:
        file.write(f"{self.customer_name} due amount is {self.amount}")

customer = Customer("John", "Smith", "[email protected]")
bill = Bill(100, customer.name)

Edit: A user dubbed this question as a duplicate, but that question is about passing attributes between different methods in the same class. My question is about passing attributes between different classes.

1 Answers1

0

Calling self.customer.name and bypassing the objects interface is the same as passing the name into the constructor.

If you properly encapsulated the customer object and passed it to the Bill would be the best solution since you would be programming to their interfaces.

class Customer:
def __init__(self, name, surname, email):
    self.name = name
    self.surname = surname
    self.email = email

def getName():
    return self.name    


class Bill:

def __init__(self, amount, customer):
    self.amount = amount
    self.customer = customer

def to_txt(self):
    with open("bill.txt", "w") as file:
        file.write(f"{self.customer.getName()} due amount is {self.amount}")





customer = Customer("John", "Smith", "[email protected]") bill = Bill(100, customer)