美文网首页
Python基础语法

Python基础语法

作者: 是立品啊 | 来源:发表于2020-09-09 06:05 被阅读0次

1. 数据类型

Numbers(数字)

  • 数字类型分3种:int(有符号整型)、float(浮点型)、complex(复数)(说明:Python 3中已去除long类型,与int类型合并)
def testDataType():
    age = 18        # int
    weight = 62.51  # float
    isAdult = True  # bool,只有True和False两个枚举值
    name = "Tony"   # string
    print("age:", age, " type:", type(age))
    print("weight:", weight, " type:", type(weight))
    print("isAdult:", isAdult, " type:", type(isAdult))
    print("name:", name, " type:", type(name))

    # 变量的类型可以直接改变
    age = name
    print("age:", age)

    a = b = c = 5
    # a,b,c三个变量指向相同的内存空间,具有相同的值
    print("a:", a, "b:", b, "c:", c)
    print("id(a):", id(a), "id(b):", id(b), "id(c):", id(c))

String(字符串)

  • 字符串用""或者''引起来
  • 字符串支持切片操作,是可迭代对象
name  = 'jack'
_name = name[0:1]

List(列表)

  • List(列表)是Python中使用最频繁的数据类型,用“[]”标识。列表可以完成大多数集合类的数据结构实现。
  • 一个List中还可以同时包含不同类型的数据,支持字符、数字、字符串,甚至可以包含列表(即嵌套)。
  • 切片:列表中值的切割也可以用到变量[头下标:尾下标],这样就可以截取相应的列表,从左到右索引默认从0开始,从右到左索引默认从-1开始,下标可以为空(表示取到头或尾)
def testList():
    list1 = ['Thomson', 78, 12.58, 'Sunny', 180.2]
    list2 = [123, 'Tony']
    print("list1:", list1)  # 输出完整列表
    print("list1[0]:", list1[0])  # 输出列表的第一个元素
    print("list1[1:3]:", list1[1:3])  # 输出第二个至第三个元素
    print("list1[2:]:", list1[2:])  # 输出从第三个开始至列表末尾的所有元素
    print("list2 * 2 :", list2 * 2)  # 输出列表两次
    print("list1 + list2 :", list1 + list2)  # 打印组合的列表
    list1[1] = 100
    print("设置list[1]:", list1)  # 输出完整列表
    list1.append("added data")
    print("list添加元素:", list1)  # 输出增加后的列表

Tuple(元组)

  • 用“()”标识,内部元素用逗号隔开。元组不能二次赋值,相当于只读列表
def testTuple():
    tp1 = ('Thomson', 78, 12.58, 'Sunny', 180.2)
    tp2 = (123, 'Tony')
    print("tp1:", tp1)  # 输出完整元组
    print("tp2:", tp2)  # 输出完整元组
    print("tp1[0]:", tp1[0])  # 输出元组的第一个元素
    print("tp1[1:3]:", tp1[1:3])  # 输出第二个至第三个的元素
    print("tp1[2:]:", tp1[2:])  # 输出从第三个开始至列表末尾的所有元素
    print("tp2 * 2:", tp2 * 2)  # 输出元组两次
    print("tp1 + tp2:", tp1 + tp2)  # 打印组合的元组
    # tp1[1] = 100 # 不能修改元组内的元素

Dictionary(字典)

  • 字典用“{}”标识,由索引(key)和它对应的值value组成。
  • 列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典中的元素通过键存取
def testDictionary():
    dict1 = {}
    dict1['one'] = "This is one"
    dict1[2] = "This is two"
    dict2 = {'name': 'Tony', 'age': 24, 'height': 177}

    print("dict1:", dict1)
    print("dict1['one']:", dict1['one'])  # 输出键为'one' 的值
    print("dict1[2]:", dict1[2])  # 输出键为 2 的值
    print("dict2:", dict2) # 输出完整的字典
    print("dict2.keys():", dict2.keys())  # 输出所有键
    print("dict2.values():", dict2.values())  # 输出所有值

Set(集合)

  • 集合(set)是一个无序的不重复元素序列。

  • 可以使用大括号 { }或者 set()函数创建集合,注意:创建一个空集合必须用 set()而不是{ },因为{ }是用来创建一个空字典。

def testSet():
    friuts = {"apple", "orange", "strawberry", "banana", "apple", "strawberry"}
    print("friuts:", friuts)
    print("type of friuts:", type(friuts))
    arr = [1, 2, 3, 4, 5, 1]
    numbers = set(arr)
    print("numbers:", numbers)
    friuts.add(1)
    print("numbers add 1:", numbers)

其中,列表,元组,字典,集合为容器类型

2. 类

类的定义

  • 使用class语句来创建一个新类,class之后为类的名称并以冒号结尾
  • 类的帮助信息可以通过 ClassName._doc_查看,类体(class_suite)由类成员方法数据属性组成
class Test:
    "这是一个测试类"

    def __init__(self):
        self.__ivalue = 5

    def getvalue(self):
        return self.__ivalue

def testClass():
    t = Test()
    print(t.getvalue())

类成员访问权限

  • __foo__:定义的是特殊方法,一般是系统定义名字,类似__init__()

    image.png
  • _foo:以单下画线开头时表示的是 protected 类型的变量,即保护类型只允许其本身与子类进行访问,不能用于 from module import *

  • __foo:以双下画线开头时,表示的是私有类型(private)的变量,即只允许这个类本身进行访问。

类的继承

  • 继承语法 class 子类(父类):类体
  • 继承特点说明
    • 在继承中基类的初始化方法_init_()不会被自动调用,它需要在其派生类的构造中亲自专门调用
    • 在调用基类的方法时,需要使用super()前缀
    • 先在本类中查找调用的方法,找不到才去基类中找
    • 可以多继承
class Person:
    "人"
    visited = 0

    def __init__(self, name, age, height):
        self.__name = name      # 私有成员,访问权限为private
        self._age = age         # 保护成员,访问权限为protected
        self.height = height    # 公有成员,访问权限为public

    def getName(self):
        return self.__name

    def getAge(self):
        return self._age

    def showInfo(self):
        print("name:", self.__name)
        print("age:", self._age)
        print("height:", self.height)
        print("visited:", self.visited)
        Person.visited = Person.visited +1

class Teacher(Person):
    "老师"

    def __init__(self, name, age, height):
        super().__init__(name, age, height)
        self.__title = None

    def getTitle(self):
        return self.__title

    def setTitle(self, title):
        self.__title = title

    def showInfo(self):
        print("title:", self.__title)
        super().showInfo()


def testPerson():
    "测试方法"
    tony = Person("Tony", 25, 1.77)
    tony.showInfo()
    print()

    jenny = Teacher("Jenny", 34, 1.68)
    jenny.setTitle("教授")
    jenny.showInfo()

相关文章

网友评论

      本文标题:Python基础语法

      本文链接:https://www.haomeiwen.com/subject/covjektx.html