Skip to content
Advertisement

How to return objects from methods in Python?

Can anyone describe how to return objects from a method on which further methods and attributes can be accessed?

Example:

pizza = PizzaHut()
order = pizza.order()
print order.order_number
order.cancel()

Advertisement

Answer

Create an Order class with appropriate methods and properties. After that, you’ll be able to return an instance of this class from PizzaHut.order() method.

class Order(object):
    def __init__(self, number, amount):
        self.number = number
        self.amount = amount
        print self
    
    def __str__(self):
        return "Order #%s: amount = %s" % (self.number, self.amount)
        
    @property
    def order_number(self):
        return self.number

    def cancel(self):
        self.amount = 0
        print "Order is cancelled."
        print self
        

class PizzaHut(object):
    
    def __init__(self, price):
        self.price = price

    def order(self):
        return Order(42, self.price)

pizza = PizzaHut(4.99)
order = pizza.order()
print order.order_number
order.cancel()

http://repl.it/WWB


Python 3 version

class Order:
    def __init__(self, number, amount):
        self.number = number
        self.amount = amount
        print(self)
    
    def __str__(self):
        return f'Order #{self.number}: amount = {self.amount}'
        
    @property
    def order_number(self):
        return self.number

    def cancel(self):
        self.amount = 0
        print('Order is cancelled.')
        print(self)
        

class PizzaHut:
    def __init__(self, price):
        self.price = price

    def order(self):
        return Order(42, self.price)

pizza = PizzaHut(4.99)
order = pizza.order()
print(order.order_number)
order.cancel()

Py3 repl: https://replit.com/@f0t0n/so-25158930#main.py

Advertisement