明星拆包自己的课程

时间:2016-05-23 20:39:39

标签: python class python-3.x iterable-unpacking

我想知道是否可以使用自己的类进行星形解包,而不仅仅使用像<?php if (isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"]) > 0) { echo '<div class="cart-view-table-front" id="view-cart">'; echo '<h3>Your Shopping Cart</h3>'; echo '<form method="post" action="cart_update.php">'; echo '<table width="100%" cellpadding="6" cellspacing="0">'; echo '<tbody>'; $total = 0; $b = 0; foreach ($_SESSION["cart_products"] as $cart_itm) { $product_name = $cart_itm["product_name"]; $product_qty = $cart_itm["product_qty"]; $product_price = $cart_itm["product_price"]; $product_code = $cart_itm["product_code"]; $product_color = $cart_itm["product_color"]; $bg_color = ($b++ % 2 == 1) ? 'odd' : 'even'; //zebra stripe echo '<tr class="' . $bg_color . '">'; echo '<td>Qty <input type="text" size="3" maxlength="3" name="product_qty[' . $product_code . ']" value="' . $product_qty . '" /></td>'; echo '<td>' . $product_name . '</td>'; echo '<td><input type="checkbox" name="remove_code[]" value="' . $product_code . '" /> Remove</td>'; echo '</tr>'; $subtotal = ($product_price * $product_qty); $total = ($total + $subtotal); } echo '<td colspan="4">'; echo '<button type="submit">Update</button><a href="view_cart.php" class="button">Checkout</a>'; echo '</td>'; echo '</tbody>'; echo '</table>'; $current_url = urlencode($url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); echo '<input type="hidden" name="return_url" value="' . $current_url . '" />'; echo '</form>'; echo '</div>'; } ?> list这样的内置函数。

tuple

能够写

class Agent(object):
    def __init__(self, cards):
        self.cards = cards
    def __len__(self):
        return len(self.cards)
    def __iter__(self):
        return self.cards

但我明白了:

agent = Agent([1,2,3,4])
myfunc(*agent)

为了使解包成为可能,我必须实施哪些方法?

1 个答案:

答案 0 :(得分:9)

异常消息:

  *之后的

参数必须是序列

应该说,argument after * must be an iterable

因此,star-unpacking通常被称为“iterable unpacking”请参阅PEP 448 (Additional Unpacking Generalizations)PEP 3132 (Extended Iterable Unpacking)

编辑:看起来像fixed for python 3.5.2 and 3.6。将来会说:

  *之后的

参数必须是可迭代的

为了让星形解包,你的类必须是一个可迭代的,即它必须定义一个返回迭代器的__iter__

class Agent(object):
    def __init__(self, cards):
        self.cards = cards
    def __len__(self):
        return len(self.cards)
    def __iter__(self):
        return (card for card in self.cards)

然后:

In [11]: a = Agent([1, 2, 3, 4])

In [12]: print(*a)  # Note: in python 2 this will print the tuple
1 2 3 4