Python学习记录7:基础知识-类


本篇博客为 python学习记录系列博客内容,欢迎访问 python速成博客导航

👉不会吧,都2021年了还有人不会Python?三天急速入门教程!👈


1、类的基础操作
  1. 创建和使用类
# 首先我们先创建一个名为 Dog 的类(python中首字母大写的名字为类名)
class Dog():
    """A simple attempt to model a dog.""" # 文档字符串注释
    
    # _init_()方法比较特殊,创建新实例时会自动运行 (def后面的名为“方法”)
    # 在方法定义中self形参必不可少,python会自动传入self实参,我们不用管
    def __init__(self, name, age):
        """Initialize name and age attributes."""
        self.name = name # 以self为前缀的变量可供类中的所有方法使用
        self.age = age 
        
    def sit(self):
        """Simulate a dog sitting in response to a command."""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """Simulate rolling over in response to a command."""
        print(self.name.title() + " rolled over!")
        
# 创建两个实例
my_dog = Dog('willie', 6)
your_dog = Dog('lucy', 3)
# 用 句点法 访问属性
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.") # 注意将数字转化为字符串! 
my_dog.sit()

print("\nYour dog's name is " + your_dog.name.title() + ".")
print("Your dog is " + str(your_dog.age) + " years old.")
your_dog.sit()
output:
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.

Your dog's name is Lucy.
Your dog is 3 years old.
Lucy is now sitting.
  1. 给属性指定修改默认值:
"""A class that can be used to represent a car."""

class Car():
    """A simple attempt to represent a car."""

    def __init__(self, manufacturer, model, year):
        """Initialize attributes to describe a car."""
        self.manufacturer = manufacturer
        self.model = model
        self.year = year
        self.odometer_reading = 0
        # 👆类中的每个属性都必须有初始值。在方法_init__()内指定初始值后就无需包含为
        # (接上句)它提供初始值的形参。
        
    def get_descriptive_name(self):
        """Return a neatly formatted descriptive name."""
        long_name = str(self.year) + ' ' + self.manufacturer + ' ' + self.model
        return long_name.title()
    
    def read_odometer(self):
        """Print a statement showing the car's mileage."""
        print("This car has " + str(self.odometer_reading) + " miles on it.")

    def update_odometer(self, mileage):
        """
        Set the odometer reading to the given value.
        Reject the change if it attempts to roll the odometer back.
        """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    
    def increment_odometer(self, miles):
        """Add the given amount to the odometer reading."""
        self.odometer_reading += miles
my_used_car = Car('五菱宏光','至尊顶配','1999')
print(my_used_car.get_descriptive_name())

my_used_car.update_odometer(23500)
my_used_car.read_odometer()

my_used_car.increment_odometer(100)
my_used_car.read_odometer()
output:
1999 五菱宏光 至尊顶配
This car has 23500 miles on it.
This car has 23600 miles on it.
2、继承
  1. 关于子类
"""A set of classes that can be used to represent electric cars."""
# 引用Car类
from car import Car

class Battery():
    """A simple attempt to model a battery for an electric car."""

    def __init__(self, battery_size=60):
        """Initialize the batteery's attributes."""
        self.battery_size = battery_size

    def describe_battery(self):
        """Print a statement describing the battery size."""
        print("This car has a " + str(self.battery_size) + "-kWh battery.")  
        
    def get_range(self):
        """Print a statement about the range this battery provides."""
        if self.battery_size == 60:
            range = 140
        elif self.battery_size == 85:
            range = 185
            
        message = "This car can go approximately " + str(range)
        message += " miles on a full charge."
        print(message)

#Car类的子类
class ElectricCar(Car):
    """Models aspects of a car, specific to electric vehicles."""

    def __init__(self, manufacturer, model, year):
        """
        初始化父类的属性👆,在初始化电动汽车特有的属性👇
        """
        super().__init__(manufacturer, model, year)
        self.battery = Battery() #batter变量使用Battery类
	# 如果想重写父类的方法,def一个同名方法即可。
  1. 导入类:
    1.from (文件名) import (类名)
    2.import (文件名) 导入整个模块(这样做不怕重名,因为要用句点法访问)
    3.from (文件名) import *导入模块中的所有类(不推荐使用,有可能会重名
  2. Python标准库:
    这里只做简单介绍,如collections模块中的OrderedDict类,它相当于一个有序的字典。
from collections import OrderedDict

favorite_languages = OrderedDict()

favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'

for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " +
        language.title() + ".")
output:
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.
(是有序的)
  1. 类编码风格(驼峰命名法):
    1. 类名中的每个单词首字母都大写,而使用下划线;
    2. 实例名和模块名都采用小写格式,并在每个单词之间采用下划线
    3. 每个类、模块定义后面紧跟一个文档字符串注释;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值