Skip to content

Override operator in Python class #24

@muadong200474

Description

@muadong200474
class Expense:
    def __init__(self, name, cost):
        self.name = name
        self.cost = cost
        
    def get_cost(self):
        return self.cost
    
    # override '+' operator
    def __add__(self, other):
        return self.cost + other.cost
    
food = Expense("food", 100)
fuel = Expense("fuel", 50)

print(food + fuel) # output: 150

Metadata

Metadata

Assignees

No one assigned

    Labels

    PythonTipsSome tips or best practise of programming

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions