python wx模块notebook_Python模块

清疚 2023-01-10 03:39 277阅读 0赞

Python模块¶

导入模块 Import Module¶

import random

from math import pi

from math import sqrt as rt

函数Function¶

def fun(arg1, arg2):

# 函数体

参数类型限定

def fun(arg: int) -> None: # 函数返回类型

# 函数体

默认参数

def fun(arg=”default”):

# 函数体

可变数量的参数

def function(named_arg, *args):

print(named_arg)

print(args) # args是一个tuple

关键字参数Key word arguments(未提前定义的具名参数)

def my_func(x, y=7, *args, **kwargs):

print(kwargs) # kwargs是一个字典

my_func(2, 3, 4, 5, 6, a=7, b=8)

“””

{‘a’: 7, ‘b’: 8}

“””

Generator生成器¶

属于iterable,但不能随机存取。

使用yield关键字从生成器函数中返回值。

def countdown():

i = 5;

while i > 0:

yield i

i -= 1

for v in countdown():

print(v)

Decorator 装饰器¶

不修改原始函数而拓展其功能的方法。

def decor(func):

def wrap():

print(‘=================’)

func()

print(‘=================’)

return wrap

使用@注记可以使对应名字的装饰器作用于被修饰的函数。

@decor

def print_text():

print(“Hello world!”)

Lambda表达式¶

# named function

def polynomial(x):

return x**2 + 5*x + 4

print(polynomial(-4))

# lambda

print((lambda x: x**2 + 5*x + 4) (-4))

为Lambda表达式分配标识符 double = lambda x: x * 2

类¶

class Cat:

eyes = ‘blue’

def __init__(self, color, legs):

self.color = color

self.legs = legs dir(obj) 列举对象的属性和方法

构造器__init__¶

使用self作为第一个参数

静态方法与非静态方法¶

非静态方法的一个参数总是self,没有self作为参数的方法是静态方法。

Obj().method() # 非静态方法

Obj.smethod() # 静态方法

与工厂方法统一,静态方法可以使用@staticmethod修饰符。

类方法¶

类方法使用@classmethod修饰器,并接受cls作为第一个参数,返回类的一个实例。

class Square:

def __init__(self, width, length):

self.width = width

self.length = length

@classmethod

def new_square(cls, side_length):

return cls(side_length, side_length)

类继承¶

class Animal:

def __init__(self, name, color):

self.name = name

self.color = color

class Cat(Animal):

def purr(self):

print(“Purr…”)

class Dog(Animal):

def bark(self):

print(“Woof!”)

super¶

使用super关键字调用同名的基类方法。

魔术方法¶

方法名由两个下划线包围的方法称为魔术方法,如__init__和__add__。

操作符重载¶

使用魔术方法来重载操作符。 sub for -

mul for *

truediv for /

floordiv for //

mod for %

pow for **

and for &

xor for ^

or for |

重载比较 lt for <

le for <=

eq for ==

ne for !=

gt for >

ge for >=

含有特殊功能的重载 len for len()

getitem for indexing

setitem for assigning to indexed values

delitem for deleting indexed values

iter for iteration over objects (e.g., in for loops)

contains for in

封装¶

The Python philosophy is slightly different. It is often stated as “we are all consenting adults here”, meaning that you shouldn’t put arbitrary restrictions on accessing parts of a class. Hence there are no ways of enforcing a method or attribute be strictly private.

以单下划线开头的类成员不会被和数据不会被from module_name import *自动导入

名称隐藏:以双下划线开头的类成员在外部引用时需要使用不同的名称,形如_classname__method的形式

class Spam:

__egg = 7

def print_egg(self):

print(self.__egg)

s = Spam()

s.print_egg() # 7

print(s._Spam__egg) # 7

print(s.__egg) # AttributeError: ‘Spam’ object has no attribute ‘__egg’

属性¶

以字段的形式访问方法,从而使特定的字段只读或能通过方法自动生成。

支持Setter语法

class Pizza:

def __init__(self, toppings):

self.toppings = toppings

self._pineapple_allowed = False

@property

def pineapple_allowed(self):

return self._pineapple_allowed

@pineapple_allowed.setter

def pineapple_allowed(self, value):

if value:

password = input(“Enter the password: “)

if password == “Sw0rdf1sh!”:

self._pineapple_allowed = value

else:

raise ValueError(“Alert! Intruder!”)

pizza = Pizza([“cheese”, “tomato”])

print(pizza.pineapple_allowed)

pizza.pineapple_allowed = True

print(pizza.pineapple_allowed)

最后更新: 2020年11月17日

发表评论

表情:
评论列表 (有 0 条评论,277人围观)

还没有评论,来说两句吧...

相关阅读