【Python】再来继续学习__init__,self初始化参数,其他函数调用这些参数。

再来一段代码,但是我还没看出有什么区别。

有点理解了,好像是通过__init__初始化若干参数,然后接下来的几个函数调用,最后传入值。

# _*_ coding: utf-8 _*_
class Rectangle():
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def getPeri(self):
        return (self.a + self.b) * 2
    def getArea(self):
        print self.a * self.b

rect1 = Rectangle(3, 4)
rect2 = Rectangle(10, 20)
print (rect1.a)
print (rect2.b)
rect1.getArea()

运行结果:

3
20
12

 

再来一段代码 

# _*_ coding: utf-8 _*_
# 定义1个“天猫精灵”类,打印它的详情信息
# self就是用于存储对象属性的集合,初始化了3个参数
# 定义了2个函数,并进行信息输出
class TmallGenie:
    def __init__(self, model, color, price):
        self.model = model
        self.color = color
        self.price = price
    def info(self):
        print('-->天猫精灵%s,颜色为%s,价格为%s' % (self.model, self.color, self.price))
    def hello(self):
        print('-->你好,天猫精灵%s,早上好' % self.model)

# 定义了b,为类传入3个参数
b = TmallGenie('X1', 'Red', '299')
b.info()
b.hello()
print(b.__dict__)

运行结果:

-->天猫精灵X1,颜色为Red,价格为299
-->你好,天猫精灵X1,早上好
{'color': 'Red', 'model': 'X1', 'price': '299'}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值