从Python中的方法返回对象

时间:2014-08-06 11:15:18

标签: python

任何人都可以描述如何从可以访问其他方法并可以访问其属性的方法返回对象吗?例如

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

3 个答案:

答案 0 :(得分:1)

使用适当的方法和属性创建Order类。之后,您将能够从PizzaHut.order()方法返回此类的实例。

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

答案 1 :(得分:0)

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"

答案 2 :(得分:0)

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