Python 基础

创建虚拟环境:

python3 -m venv venv
source venv/bin/activate

Python 的布尔类型

flag = True and False
print('flag:', flag) # flag: False

flag = True or False
print('flag:', flag) # flag: True

flag = not False
print('flag:', flag) # flag: True

Python 的字符串 format

template = 'Hello {}'
text = 'world'
result = template.format(text)

print('r:', result) # r: Hello world

Python 的流程控制

score = 78
if(score < 60):
    print('faile!')
elif(score < 80):
    print('good!')
else:
    print('nice!')

Python 的 for 循环

text= 'python'

for char in text:
    print(char)

Python 的容器

list:

students = ['wang', 'li', 'zhang', 'liu']

# 获取元素
print(students[2], students[-2]) # zhang zhang

# 删除元素
s = students.pop()
print(s, students) # liu ['wang', 'li', 'zhang']

# 添加元素
students.append('xi')
print(students) # ['wang', 'li', 'zhang', 'xi']

dict:

scores = {
    'wang': 80,
    'liu': 78,
    'li': 100
}

print(scores['li']) # 100

scores.pop('liu')
print(scores) # {'wang': 80, 'li': 100}

tuple:
元组不允许改变:

students = ('wang', 'zh', 'qin')
# TypeError: 'tuple' object does not support item assignment

函数

函数与可变参数:

def func(*args):
    print('args length = {}, args = {}'.format(len(args), args))

func('zhang', 'peng') # args length = 2, args = ('zhang', 'peng')

可变关键字:

def func(**kwargs):
    print(('name: {}, age: {}').format(kwargs.get('name'), kwargs.get('age')))

func(name = 'wang', age = 17) # name: wang, age: 17

面向对象

class Person(object):
    __location = 'HuBei'

    # 构造方法
    def __init__(self, name, sex, age):
        # 私有属性
        self.__name = name
        self.sex = sex
        self.age = age

    # 访问私有属性
    def get_name(self):
        return self.__name

    # 类方法
    @classmethod
    def set_location(cls, location):
        cls.__location = location

    @classmethod
    def get_location(cls):
        return cls.__location


class Student(Person):
    # 执行父类的初始化方法
    def __init__(self, name, sex, age, score):
        super(Student, self).__init__(name, sex, age)
        self.score = score

    def __str__(self):
        return '姓名:{},年龄:{}'.format(self.get_name(), self.age)


student = Student('张三', 1, 17, 88)

# isinstance 判断原型
print(student.age, student.score, isinstance(student, Person), student)  # 17 88 True 姓名:张三,年龄:17

posted @ 2023-06-18 12:51  弹道偏左  阅读(14)  评论(0)    收藏  举报