Python 语法

发布于 2020-11-08  268 次阅读


变量和类型

Python3.x 整型int
可以处理任意大小的整数

a = 0b100
a = 0o100
a = 100
a = 0x100

浮点型

a = 3.14
a = 3.14e2

字符串型

a = 'hello'
a = "world"
a = '''hello
    world'''
a = """hello
    world"""

布尔型

a = True
a = False

复数类型

a = 3+j
b = 1-j
c = a*b

变量命名

Python命名大小写敏感,不要和关键字冲突
PEP8 要求:
用小写
受保护的实例属性用单个下划线开头
私有实例属性用两个下划线开头

可以使用Python中内置的函数对变量类型进行转换。

  • int():将一个数值或字符串转换成整数,可以指定进制。
  • float():将一个字符串转换成浮点数。
  • str():将指定的对象转换成字符串形式,可以指定编码。
  • chr():将整数转换成该编码对应的字符串(一个字符)。
  • ord():将字符串(一个字符)转换成对应的编码(整数)。

元组与命名元组

fruit = ('apple','pear','orange')
sale = collections.namedtuple("sale","id c_id date quantity price")

列表

a = fruit('apple','pear')
b = list(a)
c = ['apple','pear']

集合

固定集合只能通过 frozenset 创建

s = {1,2,3,4,5,6,'aa'}
b = set()
c = set('apple')

映射类型

字典 dict

d1 = dict({"id":1928,"name":"tian"})
d2 = dict(id = 1928,name="tian")
d3 = {"id":1928,"name":"tian"}

有序字典

d = collections.OrderDict([('z',-4),('e',3)])

lambda 函数

s = lambda x: ""if x==1 else "s"
s(count)

断言

assert boolean_expression,optional_expression

class point:
    def __init__(self):
        self.x = 0

class circle(point):
    def __init__(self,radius,x=0,y=0):
        super().__init__()
        self.radius = radius

    @property
    def area(self):
        return math.pi*self.radius*self.radius

    def len(self):
        return math.pi*self.radius*2
    len = property(len)

    @property
    def radius(self):
        return self.__radius

    @radius.setter
    def radius(self,radius)
        self.__radius = radius

    @positive_result
    def calc_area(self,radius):
        return math.pi*radius*radius

函子

函子就是函数对象
任何包含了特殊方法 __call__() 的类都是函子

上下文管理器

实现两个特殊方法 __enter__() 与 __exit__()

class cm:
    def __init__(self):
        pass

    def __enter__(self):
        pass

    def __exit__(self):
        pass

    def process(self):
        pass

a = cm()
with a.process()

多继承

class a:
    def __init__(self):
        pass

class b:
    def __init__(self):
        pass

class c(a,b):
    def __init__(self):
        a.__init__(self)
        b.__init__(self)

元类

元类用于创建类

偏函数

协程

协程也是一种函数,特点在于在处理过程中可以在特定点挂起与恢复


朝闻道,夕死可矣