【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'}
发布了94 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/woshiyigerenlaide/article/details/104144452
今日推荐