'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()


Solution 1:[1]

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

Solution 2:[2]

class Foo():
    def f(self):
        print "Foo.f called"

class Bar():
    def b(self):
        return Foo()

bar = Bar()
bar.b().f() # prints "Foo.f called"

Solution 3:[3]

class Order:
   def __init__(self, number):
      self.order_number = number


class PizzaHut:
   def __init__(self):
      self.order = Order(1234)

   def order(self):
      return self.order

Solution 4:[4]

This is how to return back the object from a method

class Order(object):
    def __init__(self, number, amount):
       self.number = number
       self.amount = amount

    def cancel(self):
       self.amount = 0
       return self  #here you return back the object

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Miguel Prz
Solution 4 Anggi Permana Harianja