python学习

##字符串前缀:字符串字面量可以有一个可选的 前缀,该前缀会影响字面量内容的解析方式,例如:

b"data"
f'{result=}'
允许的前缀有:
b: 字节串字面量
r: 原始字符串
f: 格式字符串字面量 ("f-string")
t: 模板字符串字面量 ("t-string")
u: 无效果(为向后兼容而允许)

##三引号字符串:字符串也可以用三组匹配的单引号或双引号括起来。这些通常被称为 三引号字符串:

"""这是一个三引号字符串。"""

##忽略行尾

'This string will not include \
backslashes or newline characters.'

##八进制字符

'\120' == 'P'

##十六进制字符

'\x50'  =='p'

##f-字符串
格式化字符串字面值 或称 f-字符串 是带有 'f' 或 'F' 前缀的字符串字面值。 不同于其他字符串字面值,f-字符串的值不是固定的。 它们可能包含由花括号 {} 标记的 替换字段。 替换字段包含要在运行时被求值的表达式。 例如:

who = 'nobody'
nationality = 'Spanish'
f'{who.title()} expects the {nationality} Inquisition!' 
>>>'Nobody expects the Spanish Inquisition!'

##Python 中文编码

Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。
  解决方法为只要在文件开头加入 # -*- coding: UTF-8 -*- 或者 # coding=utf-8 就行了
脚本:
  #!/usr/bin/python
  # -*- coding: UTF-8 -*- 
  print( "你好,世界" )
  # coding=utf-8 的 = 号两边不要空格。
IDE Pycharm 设置步骤:
   进入 file > Settings,在输入框搜索 encoding。
   找到 Editor > File encodings,将 IDE Encoding 和 Project Encoding 设置为utf-8。    

##Python 标识符

以双下划线开头的 __foo 代表类的私有成员,以双下划线开头和结尾的 __foo__ 代表 Python 里特殊方法专用的标识,如 __init__() 代表类的构造函数。

##多行语句

total = item_one + \
        item_two + \
        item_three

##等待用户输入,按回车键后就会退出:

 raw_input("按下 enter 键退出,其他任意键显示...\n")

##标准数据类型
Python有五个标准的数据类型:

Numbers(数字)
String(字符串)
List(列表)
Tuple(元组)
Dictionary(字典)

字符串中:加号(+)是字符串连接运算符,星号(*)是重复操作
列表用 [ ] 标识,
元组用 () 标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表
字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典用"{ }"标识。字典由索引(key)和它对应的值value组成。

##Python 的字符串内建函数

不定长参数
  def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]

##文件

file object = open(file_name [, access_mode][, buffering])
     object.close()
     fileObject.write(string)
     fileObject.read([count])
     tell()
     seek(offset [,from])
     os.rename( "test1.txt", "test2.txt" )
     os.remove(file_name)
     os.mkdir("newdir")
     os.chdir("newdir")
     os.getcwd()
     os.rmdir('dirname')

##创建类

class ClassName:
   '类的帮助信息'   #类文档字符串
   class_suite  #类体,class_suite 由类成员,方法,数据属性组成。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Employee:
'所有员工的基类'
empCount = 0

def __init__(self, name, salary):         ##构造方法,类实例化时会自动调用
self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

##Python内置类属性

__dict__ : 类的属性(包含一个字典,由类的数据属性组成)
__doc__ :类的文档字符串
__name__: 类名
__module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
__bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)

##类的继承:class 派生类名(基类名)

##类的私有属性和方法: 两个下划线开头

 单下划线、双下划线、头尾双下划线说明
  __foo__: 定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的。
  _foo: 以单下划线开头的表示的是 protected 类型的变量
  __foo: 双下划线的表示的是私有类型(private)的变量

 ##自动赋值:将1到7赋值对应到MSG_DISCONNECT--MSG_EXIT_INFO

(
    MSG_DISCONNECT,
    MSG_IGNORE,
    MSG_UNIMPLEMENTED,
    MSG_DEBUG,
    MSG_SERVICE_REQUEST,
    MSG_SERVICE_ACCEPT,
    MSG_EXT_INFO,
) = range(1, 8)

 ##装饰器

--------------------------
def simple_decorator(func):
    """这是一个简单的装饰器函数"""
    def wrapper():
        print("装饰器执行前")
        func()  # 调用原始函数
        print("装饰器执行后")
    return wrapper  # 返回包装后的函数

def say_hello():
    """原始函数"""
    print("Hello!")

# 手动装饰:用装饰器包装原函数
decorated_func = simple_decorator(say_hello)
decorated_func()

--------------------------######
def simple_decorator(func):
    def wrapper():
        print("装饰器执行前")
        func()
        print("装饰器执行后")
    return wrapper

@simple_decorator            ##这里的@simple_decorator完全等价于:say_hello = simple_decorator(say_hello)
def say_hello():
    print("Hello!")

say_hello()  # 自动被装饰

参考链接:
https://www.runoob.com/w3cnote/python-func-decorators.html

 ####工厂方法模式

from abc import ABC, abstractmethod

# 产品接口
class Button(ABC):
    @abstractmethod
    def render(self):
        pass
    
    @abstractmethod
    def onClick(self):
        pass

# 具体产品
class WindowsButton(Button):
    def render(self):
        return "渲染 Windows 风格按钮"
    
    def onClick(self):
        return "Windows 按钮被点击"

class MacButton(Button):
    def render(self):
        return "渲染 Mac 风格按钮"
    
    def onClick(self):
        return "Mac 按钮被点击"

# 创建者抽象类
class Dialog(ABC):
    @abstractmethod
    def createButton(self) -> Button:
        pass
    
    def render(self):
        # 调用工厂方法创建产品
        button = self.createButton()
        result = button.render()
        return result

# 具体创建者
class WindowsDialog(Dialog):
    def createButton(self) -> Button:
        return WindowsButton()

class MacDialog(Dialog):
    def createButton(self) -> Button:
        return MacButton()

# 使用示例
def test_factory_method():
    # 根据配置选择具体的工厂
    config = "windows"  # 可以从配置文件读取
    
    if config == "windows":
        dialog = WindowsDialog()
    else:
        dialog = MacDialog()
    
    result = dialog.render()
    print(result)

if __name__ == "__main__":
    test_factory_method()

 ####抽象工厂模式

from abc import ABC, abstractmethod

# 抽象产品 A
class Button(ABC):
    @abstractmethod
    def paint(self):
        pass

# 抽象产品 B
class Checkbox(ABC):
    @abstractmethod
    def paint(self):
        pass

# 具体产品 A1
class WindowsButton(Button):
    def paint(self):
        return "渲染 Windows 按钮"

# 具体产品 A2
class MacButton(Button):
    def paint(self):
        return "渲染 Mac 按钮"

# 具体产品 B1
class WindowsCheckbox(Checkbox):
    def paint(self):
        return "渲染 Windows 复选框"

# 具体产品 B2
class MacCheckbox(Checkbox):
    def paint(self):
        return "渲染 Mac 复选框"

# 抽象工厂
class GUIFactory(ABC):
    @abstractmethod
    def createButton(self) -> Button:
        pass
    
    @abstractmethod
    def createCheckbox(self) -> Checkbox:
        pass

# 具体工厂 1
class WindowsFactory(GUIFactory):
    def createButton(self) -> Button:
        return WindowsButton()
    
    def createCheckbox(self) -> Checkbox:
        return WindowsCheckbox()

# 具体工厂 2
class MacFactory(GUIFactory):
    def createButton(self) -> Button:
        return MacButton()
    
    def createCheckbox(self) -> Checkbox:
        return MacCheckbox()

# 客户端代码
class Application:
    def __init__(self, factory: GUIFactory):
        self.factory = factory
        self.button = None
        self.checkbox = None
    
    def createUI(self):
        self.button = self.factory.createButton()
        self.checkbox = self.factory.createCheckbox()
    
    def paint(self):
        result = []
        if self.button:
            result.append(self.button.paint())
        if self.checkbox:
            result.append(self.checkbox.paint())
        return "\n".join(result)

# 使用示例
def test_abstract_factory():
    # 根据系统类型选择工厂
    system_type = "windows"  # 可以自动检测或从配置读取
    
    if system_type == "windows":
        factory = WindowsFactory()
    else:
        factory = MacFactory()
    
    app = Application(factory)
    app.createUI()
    print(app.paint())

if __name__ == "__main__":
    test_abstract_factory()

 

 

参考链接:

https://docs.python.org/zh-cn/3/reference/lexical_analysis.html#logical-lines
https://www.runoob.com/python/python-functions.html

 

posted @ 2026-07-03 08:35  hopeccie  阅读(3)  评论(0)    收藏  举报