- 帖子
- 4
- 精华
- 0
- 积分
- 24
- 阅读权限
- 10
- 注册时间
- 2013-8-31
- 最后登录
- 2015-2-14
|
先生,我在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
不知道我的意思有没有表达清楚。
谢谢。
|
|