py基础语法 下【py专栏】

函数

返回值

返回简单值

def user(first_name, middle_name, last_name):
    full_name = f"{first_name} {middle_name} {last_name}"
    return full_name;

name = user('kroos', 'klis', 'tony')
print(name)
# 输出:Kroos Klis Tony

实参可选

上述例子看出并非所有人都有middle_name。如果没有提供,那么不能正常运行,这时可以给middle_name指定一个空的默认值,没有这个形参依然可以运行,将其移到形参列表末尾。

def user(first_name, last_name,  middle_name=''):
    if middle_name:
    full_name = f"{first_name} {middle_name} {last_name}"
    else:
    full_name = f"{first_name} {last_name}"
    return full_name;

name = user('kroos', 'klis', 'tony')
print(name)
# 输出:Kroos Klis Tony

name = user('kroos', 'tony')
print(name)
# 输出:Kroos Tony

返回字典

函数可以返回任何类型的值,包括列表和字典等较复杂的数据结构

def build_person(first_name, last_name):
    person = {'first': first_name, 'last': last_name}
    return person

person = build_person('kroos', 'tony'):
print(person)
# 输出: {'first': 'kroos', 'last': 'tony'}

也可以轻松地扩展这个函数,存储其它的值

def build_person(first_name, last_name, age=None):
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age;
    return person

person = build_person('kroos', 'tony', age=18):
print(person)
# 输出: {'first': 'kroos', 'last': 'tony', 'age': 18}

传递列表

def users(names):
    for name in names:
    msg = f"Hello, {name.title()}"
    print(mag)

usernames = ['kroos', 'messi']
users(uesrnames)

# 输出: Hello, Kroos
        Hello, Messi

传递任意数量实参

有时候,预先不知道函数需要接收多少实参,那么可以用以下方式

def make_pizza(*toppings):
    print(toppings)

make_pizza('aaa')
# 输出:('aaa')
make_pizza('aaa', 'bbb', 'ccc')
# 输出:('aaa', 'bbb', 'ccc')

形参名 * 号让py创建一个名为toppings的空元组,并将收到所有值都封装到这个元组中。无论是一个值还是多个值,都可以妥善处理。

使用任意数量的关键字实参

下面示例中,函数接受名和姓,还接受任意数量的关键字实参:

def build_profile(first, last, *user_info):
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info

user = build_profile('kroos', 'tony', home='Germany')
print(user)

# 输出:{'first': 'kroos', 'last': 'tony', 'home': 'Germany'}

上述例子,我们调用build_profile,传递还有一个键值对,并将返回user_info赋值给user。

创建类

class Dog:
    # 构造函数,用于初始化Dog对象的属性
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 方法,用于打印Dog对象的信息
    def bark(self):
        print(f"{self.name} is {self.age} years old and is barking.")

# 创建一个名为"Rufus"、年龄为2岁的Dog对象
my_dog = Dog("Rufus", 2)

# 调用Dog对象的bark()方法
my_dog.bark()
# 输出结果为:"Rufus is 2 years old and is barking."

init()是Python中的一个特殊方法,也称为构造函数。它会在创建一个类的实例时被调用,并用来初始化这个实例的属性。

在一个类中,可以使用__init__()方法来定义实例化对象时需要传入的参数,并将这些参数赋值给实例的属性。

根据类创建实例

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person1 = Person("Alice", 25)

我们创建了一个Person对象person1,并在创建时传入了两个参数:"Alice"和25。这些参数会被传递给Person类的初始化方法__init__(),然后被用来初始化person1的属性name和age。

同样的方式,可以创建多个Person对象,并对每个对象的属性赋予不同的值:

person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

print(person1.name)  # 输出:"Alice"
print(person1.age)   # 输出:25

print(person2.name)  # 输出:"Bob"
print(person2.age)   # 输出:30

使用类和实例

1.创建类:使用class关键字,创建一个类,并定义类的属性和方法。
2.创建实例:使用类名后面跟一对括号,创建一个类的实例,并传入初始化方法__init__()中定义的参数。
3.访问属性:使用实例.属性的方式,访问实例的属性。
4.调用方法:使用实例.方法的方式,调用实例的方法

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

print(person1.name)    # 输出:"Alice"
print(person2.age)     # 输出:30

person1.say_hello()    # 输出:"Hello, my name is Alice and I am 25 years old."
person2.say_hello()    # 输出:"Hello, my name is Bob and I am 30 years old."

我们定义了一个Person类,它有两个属性name和age,和一个方法say_hello()。我们创建了两个Person对象person1和person2,并分别传入不同的name和age参数。然后,我们通过实例.属性和实例.方法的方式,访问了实例的属性和调用了实例的方法。
使用类和实例,可以实现更加灵活和可扩展的程序设计。

给属性指定默认的值

class Person:
    def __init__(self, name, age):
        self.name = 'kroos'
        self.age = 28

    def say_hello(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

person1 = Person("Alice", 25)
person2 = Person()

print(person1.name)    # 输出:"Alice"
print(person2.age)     # 输出:28

person1.say_hello()    # 输出:"Hello, my name is Alice and I am 25 years old."
person2.say_hello()    # 输出:"Hello, my name is kroosand I am 28 years old."

修改属性的值

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

print(person1.name)  # 输出:"Alice"
print(person2.age)   # 输出:30

person1.age = 26    # 修改person1的age属性值
person2.name = "Charlie"    # 修改person2的name属性值

person1.say_hello()    # 输出:"Hello, my name is Alice and I am 26 years old."
person2.say_hello()    # 输出:"Hello, my name is Charlie and I am 30 years old."

修改了person1的age属性值为26,修改了person2的name属性值为"Charlie"。最后,我们调用实例的方法say_hello()来输出实例的属性值,可以看到属性值已经被修改为新的值。

继承

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"{self.name} is making a sound.")

class Dog(Animal):
    def speak(self):
        print(f"{self.name} is barking.")

定义了一个父类Animal和一个子类Dog。子类Dog通过在class关键字后面加上括号,并指定要继承的父类Animal,来继承Animal类的属性和方法。在子类Dog中,重写了父类Animal的speak()方法。
使用继承后,可以创建Dog类的实例,并调用它的方法

my_dog = Dog("Rufus")
my_dog.speak()    # 输出:"Rufus is barking."

创建了一个Dog实例my_dog,并传入参数"Rufus"来初始化它的属性name。然后,我们调用了my_dog的speak()方法,会输出"Rufus is barking."。由于子类Dog重写了父类Animal的speak()方法,因此调用speak()方法时会调用子类Dog中的方法。
继承可以大大简化类的定义和管理,并可以提高代码的重用性和可读性。

文件和异常

在Python中,可以使用open()函数来读取文件。open()函数接受两个参数:文件路径和打开模式。
例如,如果要读取一个名为example.txt的文本文件,可以使用以下代码:

with open('example.txt', 'r') as f:
    content = f.read()
    print(content)

在这个示例代码中,使用了open()函数来打开example.txt文件,并指定打开模式为’r’(读取模式)。接着,使用with语句,将文件对象f赋值给变量f,并在代码块结束时自动关闭文件。需要注意的是,在使用open()函数时,应该始终使用with语句来自动关闭文件。否则,如果在代码块中出现异常而导致文件未关闭,可能会导致文件损坏或数据丢失。

逐行读取

使用for循环和readlines()方法来逐行读取文件的内容。readlines()方法会返回一个包含文件所有行的列表,然后可以使用for循环遍历该列表,逐行读取文件内容。

with open('example.txt', 'r') as f:
    lines = f.readlines()
    for line in lines:
        print(line.rstrip())

在这个示例代码中,使用了open()函数来打开example.txt文件,并指定打开模式为’r’(读取模式)。接着,使用with语句,将文件对象f赋值给变量f,并在代码块结束时自动关闭文件。

在with语句中,使用f.readlines()方法来读取文件内容,并将其赋值给变量lines。然后,使用for循环遍历lines列表,逐行读取文件内容,并使用rstrip()方法去掉每行末尾的换行符"\n"。

写入空文件

使用open()函数和write()方法来写入文件。open()函数接受两个参数:文件路径和打开模式。打开模式包括:
‘w’:写入模式,用于写入文件。如果文件不存在,则创建一个新文件;如果文件已存在,则清空文件中的内容。
‘a’:追加模式,用于在文件末尾追加内容。如果文件不存在,则创建一个新文件。

with open('example.txt', 'w') as f:
    f.write('Hello, world!')

附加到文件

如果要在文件末尾追加内容,而不是覆盖原有的内容,可以将打开模式改为’a’

with open('example.txt', 'a') as f:
    f.write('\nHi, there!')

在这个示例代码中,使用了open()函数来打开example.txt文件,并指定打开模式为’a’(追加模式)。其中"\n"表示换行符。

异常

异常是指程序运行时发生了错误导致程序无法正常执行的情况。在遇到异常时,程序会停止执行并抛出异常。如果程序未处理异常,将导致程序崩溃或出现其他不可预料的错误。

try:
    with open('example.txt', 'r') as f:
        content = f.read()
        print(content)
except FileNotFoundError:
    print("The file does not exist.")

在这个示例代码中,我们使用try语句来打开example.txt文件并读取文件内容。如果文件不存在,则会抛出FileNotFoundError异常。在except语句中,我们捕获了FileNotFoundError异常,并输出了一条错误信息。

存储数据

json.dump()和json.load()

将一个字典对象序列化为JSON格式,并写入一个名为example.json的文件中:

import json

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

with open('example.json', 'w') as f:
    json.dump(my_dict, f)

从一个名为example.json的文件中读取JSON数据,并将其反序列化为Python对象

import json

with open('example.json', 'r') as f:
    my_dict = json.load(f)
    print(my_dict)

测试代码

def add(x, y):
    return x + y

创建一个测试类,并继承unittest.TestCase类。在测试类中,使用一系列以test开头的方法来测试函数的不同方面。
例如,创建一个名为TestAdd的测试类,包含两个测试方法test_add_int

import unittest

class TestAdd(unittest.TestCase):
    def test_add_int(self):
        self.assertEqual(add(1, 2), 3)
        self.assertEqual(add(-1, 2), 1)
        self.assertEqual(add(0, 0), 0)

创建了一个名为TestAdd的测试类,并继承了unittest.TestCase类。然后,在该类中定义了两个测试方法test_add_int。test_add_int方法用于测试整数相加的功能。
在测试方法中,使用assertEqual()方法来测试函数的输出是否符合预期。
最后,执行测试代码,可以使用unittest.main()函数或者在命令行中执行测试文件:

if __name__ == '__main__':
    unittest.main()

常见的断言方法

以下是一些常见的unittest中的断言方法:
assertEqual(a, b):验证a == b,不等则测试失败。
assertNotEqual(a, b):验证a != b,相等则测试失败。
assertTrue(x):验证bool(x) is True,为False则测试失败。
assertFalse(x):验证bool(x) is False,为True则测试失败。
assertIs(a, b):验证a is b,不是则测试失败。
assertIsNot(a, b):验证a is not b,是则测试失败。
assertIsNone(x):验证x is None,不是则测试失败。
assertIsNotNone(x):验证x is not None,是则测试失败。
assertIn(a, b):验证a in b,不在则测试失败。
assertNotIn(a, b):验证a not in b,在则测试失败。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值