欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python学习笔记(七)

程序员文章站 2022-07-10 13:28:12
...

对应第九章
面向对象编程语言:

  • 类: 一个模板, (人类)—是一个抽象的, 没有实体的
  • 对象: (eg: 张三, 李四)
  • 属性: (表示这类东西的特征, 眼睛, 嘴巴, 鼻子)
  • 方法: (表示这类物体可以做的事情, eg: 吃饭, 睡觉,学习)

类的意义可以参考:

init前时双下划线__而不是_。

class Restaurant:
    def _init_(self,restaurant_name,cuisine_type):
        self.restaurant_name=restaurant_name
        self.cuisine_type=cuisine_type
        
    def describe_restaurant(self):
        print(f"a restraurant named {self.restaurant_name},which is a {self.cuisine_type} retraurant")
    
    def open_restaurant(self):
        print("open")
    
restaurant1=Restaurant('wenxian','Chinese')
restaurant1.describe_restaurant()
restaurant1.open_restaurant()
TypeError                                 Traceback (most recent call last)
<ipython-input-2-0734b3316f83> in <module>
     10         print("open")
     11 
---> 12 restaurant1=Restaurant('wenxian','Chinese')
     13 restaurant1.describr_restaurant()
     14 restaurant1.open_restaurant()

TypeError: Restaurant() takes no arguments

class中定义的其他方法中调用属性的时候必须使用形参self.model

集成父类super的init参数不需要self,但是类中的方法只要需要一个参数self

class Restaurant:
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name=restaurant_name
        self.cuisine_type=cuisine_type
        
    def describe_restaurant(self):
        print(f"a restraurant named {self.restaurant_name},which is a {self.cuisine_type} retraurant")
    
    def open_restaurant(self):
        print("open")

class IceCreamStand(Restaurant):
    def __init__(self,restaurant_name,cuisine_type):
        super().__init__(self,restaurant_name,cuisine_type)
        flavors=['one','two','three']
        self.flavors=['one','two','three']
        
    def show():
        print(self.flavors)
        
ice1=IceCreamStand('lili','iceream')
ice1.show()

TypeError                                 Traceback (most recent call last)
<ipython-input-15-fcfe2a1a3f62> in <module>
     19         print(self.flavors)
     20 
---> 21 ice1=IceCreamStand('lili','iceream')
     22 ice1.show()

<ipython-input-15-fcfe2a1a3f62> in __init__(self, restaurant_name, cuisine_type)
     12 class IceCreamStand(Restaurant):
     13     def __init__(self,restaurant_name,cuisine_type):
---> 14         super().__init__(self,restaurant_name,cuisine_type)
     15         flavors=['one','two','three']
     16         self.flavors=['one','two','three']

TypeError: __init__() takes 3 positional arguments but 4 were given