共读Python编程-类卡

2019-06-19  本文已影响0人  铺床高手

创建和使用类

创建类

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")

使用类

my_dog = Dog("kim",2)
my_dog .name
my_dog.sit()

类的使用

给属性指定默认值

class Car():
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

修改属性的值

my_new_car.odometer_reading = 23
def update_odometer(self, mileage):
        if mileage < self.odometer_reading:
            print("you can't roll back an odometer")
            return
        self.odometer_reading = mileage
def increament_odometer(self, mileage):
        if mileage < 0:
            print("you can't roll back an odometer")
            return
        self.odometer_reading += mileage

继承

格式

class Car():
    ....


class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)

重写父类方法

名称与父类方法相同即可

将实例用做属性

当类中细节越来越多的时候可以将类拆分.将同类的属性归并到一个新的类中.在源类中使用新创建类的实例

class Car():
      --snip--

class Battery():
    def __init__(self, battery_size=70):
          self.battery_size = battery_size

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

导入类

导入单个类

from car import Car

从一个模块中导入多个类

from car import Car, ElectricCar

导入整个模块

import car

导入模块中的所有类(不推荐)

from module_name import *

Python标准库

Python 标准库是一组模块

from collections import OrderedDict

类编码风格

上一篇下一篇

猜你喜欢

热点阅读