中文语法的基本知识(2022年5月21日学习笔记-基础语法)
Python学习笔记-基础语法1、类和函数的区别,我来为大家科普一下关于中文语法的基本知识?下面希望有你要的答案,我们一起来看看吧!
中文语法的基本知识
Python学习笔记-基础语法
第九章 类- 一、创建和使用类
- 二、使用类和实例
- 三、继承
- 四、导入模块
- 五、Python标准库
- 六、注
1、类和函数的区别
- 类(class):类是面向对象的,class可以保存一此属性的状态,同时也起到模板的作用,把一些通用的东西写进类定义中,也就是在’init’中。class有点像是将多个函数进行功能性封装
- 函数:函数更像是面向过程编程,更易理解,但是当系统较大时,重复性就会增多。
- 使用class Name() 来创建一个Name类,类中包含许多方法(函数),根据类来创建实例XingMing = Name(),实例可以用句点表示法调用类中的方法。
- 一个类包含了一系列实例的通性,众多根据类创建的实例可以使用句点表示法调用类中的方法。
2、创建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!")
my_dog = Dog('willie', 6)
print("My dog's name is " my_dog.name.title() ".")
print("My dog is " str(my_dog.age) " years old.")
my_dog.sit()
my_dog.roll_over()
输出结果为:
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.
Willie rolled over!
- 在Python中,首字母大写的名称指的是类,因为要从空白创建这个类,所以类定义中的括号是空的。
- _ init _ ()是类中的默认方法,每次根据类创建实例时,Python都会自动运行它。
- 形参self必不可少,Python调用_ init _()方法来创建实例时,将自动传入实参self。每个与类相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。
- 创建Dog实例时,Python将调用Dog类的方法_ init _(),通过实参向Dog()传递名字和年龄;self会自动传递,因此我们不需要传递它。每当我们根据Dog类创建实例时,都只需给最后两个形参(name和age)提供值。
- 以self为前缀的变量都可供类中的所有方法使用,可以通过类的任何实例来访问这些变量。
- 像self.name、self.age这样可以通过实例访问的变量称为属性。
- 属性参数传递给_ init _,使用self.属性来给实例赋予属性。
- 访问属性:my_dog.name,Python先找到实例my_dog,再查找与这个实例相关联的属性。
- 调用方法:my_dog.sit()。
- 创建实例后,以实例名替代self,如my_dog.name相当于self.name。
class People():
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def walk(self):
print(self.name.title() " is now walking on the road.")
def die(self):
print(self.name.title() "'s weight is " str(self.weight) " when he was sent to the crematorium.")
zhang = People('Zhang San', 18, 200)
print(zhang.name.title() " is " str(zhang.age) " years old.")
zhang.walk()
zhang.die()
输出结果为:
Zhang San is 18 years old.
Zhang San is now walking on the road.
Zhang San's weight is 200 when he was sent to the crematorium.
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('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
输出结果为:
2016 Audi A4.
2、给属性指定默认值
- 直接在方法中创建一个变量,并赋予初始默认值
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 #赋予默认值0
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
输出结果为:
2016 Audi A4.
This car has 0 miles on it.
- 也可像给形参赋予默认值一样:(更易理解)
class Car():
def __init__(self,make,model,year,odometer_reading=0):
self.make = make
self.model = model
self.year = year
self.odometer_reading = odometer_reading
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
输出结果:
2016 Audi A4.
This car has 0 miles on it.
3、直接修改属性的值
- 可在类外直接对该变量进行赋值,此时Python会使用新赋予的值而非默认值
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 #赋予默认值0
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
my_new_car = Car('audi', 'a4', 2016)
my_new_car.odometer_reading = 23
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
输出结果为:
2016 Audi A4.
This car has 23 miles on it.
- 也可在定义实例时直接传入实参
class Car():
def __init__(self,make,model,year,odometer_reading=0):
self.make = make
self.model = model
self.year = year
self.odometer_reading = odometer_reading
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
my_new_car = Car('audi', 'a4', 2016,23)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
输出结果为:
2016 Audi A4.
This car has 23 miles on it.
- 通过方法修改属性的值
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 10 #赋予默认值10
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
my_new_car = Car('audi', 'a4', 2016)
my_new_car.update_odometer(5)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
输出结果为:
You can't roll back an odometer!
2016 Audi A4.
This car has 10 miles on it.
- 通过方法对属性的值进行递增
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 10 #赋予默认值10
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
if miles >= 0:
self.odometer_reading =miles
else:
print("You can't roll back an odometer!")
my_used_car = Car('audi', 'a4', 2016)
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()
输出结果为:
2016 Audi A4.
This car has 23500 miles on it.
This car has 23600 miles on it.
- 编写类时,并非总要从空白开始,若要编写的类时另一个线现成类的特殊版本,可使用继承。
- 一个类继承另一个类时,它将自动获得另一个类的所有属性和方法,原有的类称为父类,而新类称为子类。
- 子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。
- 继承:类括号非空白,使用super()函数关联父子类。
1、子类的方法_ init _()
- 创建子类的实例时,Python首先需要完成的任务是给父类的所有属性赋值。
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 10 #赋予默认值10
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
if miles >= 0:
self.odometer_reading =miles
else:
print("You can't roll back an odometer!")
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
输出结果为:
2016 Tesla Model S.
- 创建子类时,父类必须包含在当前文件中,且位于子类前面。
- 定义子类时,必须在括号内指定父类的名称:ElectricCar(Car)。
- super()是一个特殊函数,帮助Python将父类与子类关联起来。
- super()._ init (make, model, year) 这行代码让Python调用ElectricCar的父类的方法 init _(),让ElectricCar实例包含父类的所有属性,父类也成为超类(superclass)。
2、给子类定义属性和方法
- 让一个类继承另一类后,可添加区分子类和父类所需的新属性和方法。
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 10 #赋予默认值10
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
if miles >= 0:
self.odometer_reading =miles
else:
print("You can't roll back an odometer!")
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
print("This car has a " str(self.battery_size) "-kwh battery.")
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
输出结果为:
2016 Tesla Model S.
This car has a 70-kwh battery.
3、重写父类的方法
- 对于父类的方法,只要它不符合子类模拟的实物的行为,都可对其进行重写。
- 可在子类中定义一个与要重写的父类方法同名的方法,这样Python将不会考虑这个父类方法,而只关注在子类中定义的相应方法。
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 10 #赋予默认值10
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
if miles >= 0:
self.odometer_reading =miles
else:
print("You can't roll back an odometer!")
def fill_gas_tank(self):
print("This car doesn't need a gas tank!")
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
print("This car has a " str(self.battery_size) "-kwh battery.")
def fill_gas_tank(self):
print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()
输出结果为:
2016 Tesla Model S.
This car has a 70-kwh battery.
This car doesn't need a gas tank!
4、将实例用作属性
- 将一个大型类拆分成多个协同工作的小类,并将这些小类的实例用作其他类的一个属性。
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 10 #赋予默认值10
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
if miles >= 0:
self.odometer_reading =miles
else:
print("You can't roll back an odometer!")
def fill_gas_tank(self):
print("This car doesn't need a gas tank!")
class Battery():
def __init__(self,battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " str(self.battery_size) "-kwh battery.")
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make, model, year)
self.battery = Battery()
def fill_gas_tank(self):
print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.fill_gas_tank()
my_tesla.battery.describe_battery()
输出结果为:
2016 Tesla Model S.
This car doesn't need a gas tank!
This car has a 70-kwh battery.
- 在其他类中使用实例作为属性:self.类,然后再定义实例时:name.类.function即可。
- slef.battery让Python创建一个新的Battery实例(由于没有指定尺寸,因此为默认值70),并将该实例存储在属性self.battery中。
- 每当方法_ init _()被调用时,都将执行该操作;因此现在每个ElectricCar实例都包含一个自动创建的Battery实例。
- my_tesla.battery.describe_battery()让Python在实例my_tesla中查找属性battery,并对存储在该属性中的Battery实例调用方法describe_battery()。
5、根据电池容量修改续航里程
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 10 #赋予默认值10
def get_descriptive_name(self):
long_name = str(self.year) ' ' self.make ' ' self.model '.'
return long_name.title()
def read_odometer(self):
print("This car has " str(self.odometer_reading) " miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
if miles >= 0:
self.odometer_reading =miles
else:
print("You can't roll back an odometer!")
def fill_gas_tank(self):
print("This car doesn't need a gas tank!")
class Battery():
def __init__(self,battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " str(self.battery_size) "-kwh battery.")
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " str(range)
message =" miles on a full charge. "
print(message)
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make, model, year)
self.battery = Battery()
def fill_gas_tank(self):
print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.fill_gas_tank()
my_tesla.battery = Battery(85) #修改电池默认值
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
输出结果为:
2016 Tesla Model S.
This car doesn't need a gas tank!
This car has a 85-kwh battery.
This car can go approximately 270 miles on a full charge.
- 与从其他模块导入函数方法一致
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() '.')
输出结果为:
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.
- 字典能将信息关联起来,但不记录添加键-值对的顺序。
- 使用collections中的OrderedDict类可以创建字典并记录其中的键-值对的添加顺序。
- 类名单词首字母大写,不使用下划线;实例名和模块名都采用小写,单词之间加上下划线。
- 每个类后都应紧定义一个文档字符串简要描述类的功能。
- 用一个空行分隔方法,用两个空行分隔类。
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com