zoukankan      html  css  js  c++  java
  • 【Python编程:从入门到实践】chapter9 类

    chapter9 类
    9.1 创建和使用类
    9.1.1 创建Dog类
    class Dog():
    """一次模拟小狗的简单尝试"""
    def _init_(self, name, age):
    self.name = name
    self.age = age

    def sit(self):
    print(self.name.title()+"is now sitting.")

    def roll_over(self):
    print(self.name.title() + "rolled over!")

    1:方法_init_()
    每当根据Dog类创建新实例时,Python都会自动运行它。
    2:在Python2.7中创建类时,需要做细微的修改-在括号内包含单词object:
    class ClassName(object)
    9.1.2 根据类创建实例
    my_dog = Dog('willie', 6)
    print("My dog's name is" + my_dog.name.titile() + “。)
    print("My dog is" + str(my_dog.age) + "year old.")
    1:访问属性
    2:调用方法
    3:创建多个实例
    9.2 使用类和实例
    9.2.1 Car类
    class Car():
    def _init_(self,make,model,year):
    self.make = make
    self.model = model
    self.year = year

    def get_descriptive_name(self):
    long_name = str(self.year)+' '+self.make+' '+self.model
    return long_name.title()

    my_new_car = Car('audio', 'a4', 2016)
    print(my_new_car.get_descriptive_name())
    9.2.2 给属性指定默认值
    9.2.3 修改属性的值
    1:直接修改属性的值
    2:通过方法修改属性的值
    3:通过方法对属性的值进行递增
    9.3 继承
    9.3.1 子类的方法_init_()
    创建子类的实例时,Python首先需要完成的任务是给父类的所有属性赋值。
    为此,子类的方法_init_()需要父类是以援手。

    class ElectricCar(Car):

    def _init_(self,make,model,year):
    super()._init_(make,model,year)

    my_tesla = ElectricCar("tesal","models",2016)
    9.3.2 Python 2.7中继承
    class Car(object):
    def _init_(self,make,model,year):
    --snip--

    class ElectricCar(Car):
    def _init_(self,make,model,year):
    super(EletricCar,self)._init_(make, model, yeat)
    --snip--
    9.3.3 给子类定义属性和方法
    9.3.4 重写父类的方法
    9.3.5 将实例用作属性
    class Battery():
    def _init_(self,battrty_size= 70):
    self.battery_size = battery_size

    class ElectricCar(Car):
    def _init_(self,make,model,year):
    super()._init_(make,model,year)
    self.battery = Battery()

    9.4 导入类
    9.4.1 导入单个类
    from car import Car
    9.4.2 在一个模块中存储多个类
    9.4.3 从一个模块总导入多个类
    from car import Car, ElectricCar
    9.4.4 导入整个模块
    import car
    9.4.5 导入模块中的所有类
    from module_name import *
    9.4.6 在一个模块中导入另一个模块
    9.4.7 自定义工作流程

    9.5 Python标准库
    9.6 类编码风格

    作者:长风 Email:844064492@qq.com QQ群:607717453 Git:https://github.com/zhaohu19910409Dz 开源项目:https://github.com/OriginMEK/MEK 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利. 感谢您的阅读。如果觉得有用的就请各位大神高抬贵手“推荐一下”吧!你的精神支持是博主强大的写作动力。 如果觉得我的博客有意思,欢迎点击首页左上角的“+加关注”按钮关注我!
  • 相关阅读:
    2020暑假牛客多校9 B
    2020暑假牛客多校10 C -Decrement on the Tree (边权转点权处理)
    HDU 5876 补图的最短路
    CSP初赛复习
    遗传算法
    排列组合
    和式 sigma的使用
    多项式的各种操作
    三分
    NOIP2018普及游记
  • 原文地址:https://www.cnblogs.com/zhaohu/p/8099778.html
Copyright © 2011-2022 走看看