设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: crossin先生
打印 上一主题 下一主题

集中答疑专用贴

  [复制链接]

0

主题

0

好友

24

积分

新手上路

Rank: 1

楼主
发表于 2015-2-14 21:22:51 |显示全部楼层
先生,我在codecademy上学习python,也结合您的教程来看。但是学到class那一章,完全混乱掉。
它给了个例子,如下



class ShoppingCart(object):
    """Creates shopping cart objects
    for users of our fine website."""
    items_in_cart = {}
    def __init__(self, customer_name):
        self.customer_name = customer_name

    def add_item(self, product, price):
        """Add product to the cart."""
        if not product in self.items_in_cart:
            self.items_in_cart[product] = price
            print product + " added."
        else:
            print product + " is already in the cart."

    def remove_item(self, product):
        """Remove product from the cart."""
        if product in self.items_in_cart:
            del self.items_in_cart[product]
            print product + " removed."
        else:
            print product + " is not in the cart."
my_cart=ShoppingCart('cap')
my_cart.add_item('cap','10')

关于这个例子,我很疑惑:
1,在第二函数,也就是def add_item(self, product, price)这个函数,为什么加入了product和price两个变量,不加上self.product=product,self.price=price.或者不直接在第一个init中定义好。
我很疑惑,居然这一部分的代码没有报错。
2,所以,彻底糊涂在这个self.**。什么时候一定要用这个句式,什么时候一定要在init中写好self.price,什么时候在code一个新的函数的时候不能直接写price而是要写self.price

不知道我的意思有没有表达清楚。
谢谢。






回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-17 10:09 , Processed in 0.023325 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部