“Py3 oop”的版本间的差异
跳到导航
跳到搜索
(→类对象) |
|||
(未显示同一用户的10个中间版本) | |||
第297行: | 第297行: | ||
== multiprocess模块的Pool类创建多进程== | == multiprocess模块的Pool类创建多进程== | ||
<pre> | <pre> | ||
+ | from multiprocessing import Pool,cpu_count | ||
+ | import time | ||
+ | import os | ||
+ | def long_time_task(i): | ||
+ | print('子进程 {} - 任务{}'.format(os.getpid(),i)) | ||
+ | time.sleep(2) | ||
+ | print("结果:{}".format(8 ** 20)) | ||
+ | |||
+ | if __name__ == '__main__': | ||
+ | print('cpu core num: {}'.format(cpu_count())) | ||
+ | print('当前mothe 进程: {}'.format(os.getpid())) | ||
+ | start = time.time() | ||
+ | p = Pool(12) | ||
+ | for i in range(5): | ||
+ | p.apply_async(long_time_task,args=(i,)) | ||
+ | print('等所有子进程完成') | ||
+ | p.close() | ||
+ | p.join() | ||
+ | end = time.time() | ||
+ | print('总共耗时: {}'.format(end - start)) | ||
+ | |||
+ | # cpu core num: 12 | ||
+ | # 当前mothe 进程: 40772 | ||
+ | # 等所有子进程完成 | ||
+ | # 子进程 40776 - 任务0 | ||
+ | # 子进程 40777 - 任务1 | ||
+ | # 子进程 40778 - 任务2 | ||
+ | # 子进程 40779 - 任务3 | ||
+ | # 子进程 40780 - 任务4 | ||
+ | # 结果:1152921504606846976结果:1152921504606846976 | ||
+ | |||
+ | # 结果:1152921504606846976 | ||
+ | # 结果:1152921504606846976 | ||
+ | # 结果:1152921504606846976 | ||
+ | # 总共耗时: 2.0383548736572266 | ||
</pre> | </pre> | ||
+ | ==多进程间的数据共享与通信== | ||
+ | <pre> | ||
+ | from multiprocessing import Process, Queue | ||
+ | import os, time, random | ||
+ | |||
+ | # 写数据进程执行的代码: | ||
+ | def write(q): | ||
+ | print('Process to write: {}'.format(os.getpid())) | ||
+ | for value in ['A', 'B', 'C']: | ||
+ | print('Put %s to queue...' % value) | ||
+ | q.put(value) | ||
+ | time.sleep(random.random()) | ||
+ | |||
+ | # 读数据进程执行的代码: | ||
+ | def read(q): | ||
+ | print('Process to read:{}'.format(os.getpid())) | ||
+ | while True: | ||
+ | value = q.get(True) | ||
+ | print('Get %s from queue.' % value) | ||
+ | |||
+ | if __name__=='__main__': | ||
+ | # 父进程创建Queue,并传给各个子进程: | ||
+ | q = Queue() | ||
+ | pw = Process(target=write, args=(q,)) | ||
+ | pr = Process(target=read, args=(q,)) | ||
+ | # 启动子进程pw,写入: | ||
+ | pw.start() | ||
+ | # 启动子进程pr,读取: | ||
+ | pr.start() | ||
+ | # 等待pw结束: | ||
+ | pw.join() | ||
+ | # pr进程里是死循环,无法等待其结束,只能强行终止: | ||
+ | pr.terminate() | ||
+ | |||
+ | Process to write: 3036 | ||
+ | Put A to queue... | ||
+ | Process to read:9408 | ||
+ | Get A from queue. | ||
+ | Put B to queue... | ||
+ | Get B from queue. | ||
+ | Put C to queue... | ||
+ | Get C from queue. | ||
+ | </pre> | ||
+ | ==Python的多线程编程与threading模块== | ||
<pre> | <pre> | ||
+ | threading比较高级 不像thread 太底层,要做太多事 | ||
+ | |||
+ | import threading | ||
+ | import time | ||
+ | |||
+ | |||
+ | def long_time_task(i): | ||
+ | print('当前子线程: {} 任务{}'.format(threading.current_thread().name, i)) | ||
+ | time.sleep(2) | ||
+ | print("结果: {}".format(8 ** 20)) | ||
+ | |||
+ | |||
+ | if __name__=='__main__': | ||
+ | start = time.time() | ||
+ | print('这是主线程:{}'.format(threading.current_thread().name)) | ||
+ | thread_list = [] | ||
+ | for i in range(1, 3): | ||
+ | t = threading.Thread(target=long_time_task, args=(i, )) | ||
+ | thread_list.append(t) | ||
+ | |||
+ | for t in thread_list: | ||
+ | t.start() | ||
+ | |||
+ | for t in thread_list: | ||
+ | t.join() | ||
+ | |||
+ | end = time.time() | ||
+ | print("总共用时{}秒".format((end - start))) | ||
+ | |||
+ | 这是主线程:MainThread | ||
+ | 当前子线程: Thread - 1 任务1 | ||
+ | 当前子线程: Thread - 2 任务2 | ||
+ | 结果: 1152921504606846976 | ||
+ | 结果: 1152921504606846976 | ||
+ | 总共用时2.0166890621185303秒 | ||
+ | |||
+ | ➜ tmp py3 threading.py | ||
+ | Traceback (most recent call last): | ||
+ | File "/home/evan/data/python/tmp/threading.py", line 10, in <module> | ||
+ | print('当前主线程 {}'.format(threading.current_thread().name)) | ||
+ | ^^^^^^^^^^^^^^^^^^^^^^^^ | ||
+ | AttributeError: module 'threading' has no attribute 'current_thread' | ||
+ | Exception ignored in: <module 'threading' from '/home/evan/data/python/tmp/threading.py'> | ||
+ | AttributeError: module 'threading' has no attribute '_shutdown' | ||
+ | ➜ tmp | ||
</pre> | </pre> | ||
+ | <pre> | ||
+ | |||
+ | |||
+ | import threading | ||
+ | |||
+ | def say_hi(): | ||
+ | print('Hello world') | ||
+ | |||
+ | if __name__ == '__main__': | ||
+ | for i in range(3): | ||
+ | t = threading.Thread(target=say_hi) | ||
+ | t.start() #启动工作线程 target() | ||
+ | |||
+ | # Hello world | ||
+ | # Hello world | ||
+ | # Hello world | ||
+ | |||
+ | |||
+ | import threading | ||
+ | |||
+ | def say_hi(word): | ||
+ | print('Hello %s' % world) | ||
+ | |||
+ | if __name__ == '__main__': | ||
+ | for i in range(3): | ||
+ | t = threading.Thread(target=say_hi,args=('mydu',)) | ||
+ | t.start() #启动工作线程 target() | ||
+ | |||
+ | |||
+ | import subprocess | ||
+ | import threading | ||
+ | def ping(host): | ||
+ | result = subprocess.run( | ||
+ | 'ping -c2 %s &> /dev/null' % host, shell=True | ||
+ | ) | ||
+ | if result.returncode == 0: | ||
+ | print('%s:up' % host) | ||
+ | else: | ||
+ | print('%s:down' % host) | ||
+ | |||
+ | |||
+ | if __name__ == '__main__': | ||
+ | ips = ['192.168.10.%s' % i for i in range(1,6)] | ||
+ | for ip in ips: | ||
+ | t = threading.Thread(target=ping,args=(ip,)) | ||
+ | t.start() | ||
+ | |||
+ | |||
+ | #oop 化 | ||
+ | import subprocess | ||
+ | import threading | ||
+ | |||
+ | class Ping: | ||
+ | def __call__(self,host): | ||
+ | result = subprocess.run( | ||
+ | 'ping -c2 %s &> /dev/null' % host, shell=True | ||
+ | ) | ||
+ | if result.returncode == 0: | ||
+ | print('%s:up' % host) | ||
+ | else: | ||
+ | print('%s:down' % host) | ||
+ | |||
+ | |||
+ | if __name__ == '__main__': | ||
+ | ips = ['192.168.10.%s' % i for i in range(1,6)] | ||
+ | for ip in ips: | ||
+ | t = threading.Thread(target=Ping(),args=(ip,)) | ||
+ | t.start() # target(*args) | ||
+ | |||
+ | |||
+ | # 2 oop | ||
+ | import subprocess | ||
+ | import threading | ||
+ | #绑定在实例上的属性 | ||
+ | class Ping: | ||
+ | def __init__(self,host): | ||
+ | self.host = host | ||
+ | def __call__(self): | ||
+ | result = subprocess.run( | ||
+ | 'ping -c2 %s &> /dev/null' % self.host, shell=True | ||
+ | ) | ||
+ | if result.returncode == 0: | ||
+ | print('%s:up' % self.host) | ||
+ | else: | ||
+ | print('%s:down' % self.host) | ||
+ | |||
+ | |||
+ | if __name__ == '__main__': | ||
+ | ips = ['192.168.10.%s' % i for i in range(1,6)] | ||
+ | for ip in ips: | ||
+ | t = threading.Thread(target=Ping(ip)) | ||
+ | t.start() # target() | ||
+ | |||
+ | |||
+ | </pre> | ||
<pre> | <pre> | ||
</pre> | </pre> | ||
+ | |||
=类对象= | =类对象= | ||
<pre> | <pre> |
2024年11月7日 (四) 04:01的最新版本
目录
- 1 2024
- 1.1 类(Class)与对象(Object)
- 1.2 类变量(class variables)与实例变量(instance variables)
- 1.3 类方法(Class method)
- 1.4 类的私有属性(private attribute)和私有方法(private method)
- 1.5 类的继承(Inheritance)
- 1.6 super()关键字调用父类方法
- 1.7 静态变量(static variable)和静态方法(static method)
- 1.8 多进程编程与multiprocess
- 1.9 multiprocess模块的Pool类创建多进程
- 1.10 多进程间的数据共享与通信
- 1.11 Python的多线程编程与threading模块
- 2 类对象
- 3 see also
2024
类(Class)与对象(Object)
class Student: def __init__(self,name,score): self.name = name self.score = score def show(self): print("Name: {}. Score: {}".format(self.name,self.score)) student1 = Student("evan",100) print(student1) student1.show() # ➜ tmp py3 clas.py # <__main__.Student object at 0x7f007c9e9890> # Name: evan. Score: 100
类变量(class variables)与实例变量(instance variables)
class Student: # number属于类变量,定义在方法外,不属于具体实例 number =0 def __init__(self,name,score): self.name = name self.score = score # number = number + 1 ## number属于类变量,定义在方法外,不属于具体实例 Student.number = Student.number + 1 def show(self): print("Name: {}. Score: {}".format(self.name,self.score)) student1 = Student("evan",100) print(student1) student1.show() print(Student.number) print(student1.__class__.number) # ➜ tmp py3 clas.py # <__main__.Student object at 0x7fb907ed9890> # Name: evan. Score: 100 # 1 # 1
类方法(Class method)
class Student: # number属于类变量,定义在方法外,不属于具体实例 number =0 def __init__(self,name,score): self.name = name self.score = score # number = number + 1 ## number属于类变量,定义在方法外,不属于具体实例 Student.number = Student.number + 1 def show(self): print("Name: {}. Score: {}".format(self.name,self.score)) # 定义类方法,打印学生的数量 属于类的方法不使用self参数, 而使用参数cls,代表类本身。另外习惯上对类方法我们会加上@classmethod的修饰符做说明 @classmethod def total(cls): print("Total: {0}".format(cls.number)) student1 = Student("evan",100) Student.total() # Total: 1
类的私有属性(private attribute)和私有方法(private method)
class Student: # number属于类变量,定义在方法外,不属于具体实例 number =0 def __init__(self,name,score): self.name = name self.__score = score # number = number + 1 ## number属于类变量,定义在方法外,不属于具体实例 # Student.number = Student.number + 1 def show(self): print("Name: {}. Score: {}".format(self.name,self.__score)) # 定义类方法,打印学生的数量 属于类的方法不使用self参数, 而使用参数cls,代表类本身。另外习惯上对类方法我们会加上@classmethod的修饰符做说明 # @classmethod # def total(cls): # print("Total: {0}".format(cls.number)) student1 = Student("evan",100) student1.show() # Name: evan. Score: 100 student1.__score ## 打印出错,该属性不能从外部访问 class Student: # number属于类变量,定义在方法外,不属于具体实例 number =0 def __init__(self,name,score): self.name = name self.__score = score # 利用property装饰器把函数伪装成属性 @property def score(self): print("Name: {}. Score: {}".format(self.name,self.__score)) # 定义类方法,打印学生的数量 属于类的方法不使用self参数, 而使用参数cls,代表类本身。另外习惯上对类方法我们会加上@classmethod的修饰符做说明 # @classmethod # def total(cls): # print("Total: {0}".format(cls.number)) student1 = Student("evan",100) #注意: 一旦给函数加上一个装饰器@property,调用函数的时候不用加括号就可以直接调用函数了 student1.score # Name: evan. Score: 100
类的继承(Inheritance)
class SchoolMember: def __init__(self, name, age): self.name = name self.age = age def tell(self): print("Name: {}, Age: {}".format(self.name, self.age),end="") class Teacher(SchoolMember): def __init__(self,name,age,salary): SchoolMember.__init__(self,name,age)# 利用父类进行初始化 self.salary = salary def tell(self): SchoolMember.tell(self) print("Salary: {}".format(self.salary)) class Student(SchoolMember): def __init__(self,name,age,score): SchoolMember.__init__(self,name,age) self.__score = score def tell(self): SchoolMember.tell(self) print(", Score: {}".format(self.__score)) teacher1 = Teacher("Alice",25,30000) student1 = Student("evan",30,100) teacher1.tell() student1.tell() # ➜ tmp py3 clas.py # Name: Alice, Age: 25Salary: 30000 # Name: evan, Age: 30, Score: 100 # ➜ tmp
super()关键字调用父类方法
# 创建子类学生Student class Student(SchoolMember): def __init__(self, name, age, score): super().__init__(name, age) self.score = score def tell(self): super().tell() # 等同于 SchoolMember.tell(self) print('score: {}'.format(self.score))
静态变量(static variable)和静态方法(static method)
class Student: number = 0 def __init__(self, nmae,score): self.name = nmae self.score = score Student.number += 1 def show(self): print("Name: {}. Score: {}".format(self.name, self.score)) # 静态方法无法使用cls和self参数访问类或实例的变量 @staticmethod def func1(): print("this is a static method")
多进程编程与multiprocess
import time import os def long_time_task(): print('当前里程id {0}'.format(os.getpid())) time.sleep(2) print("结果:{}".format(8 ** 20)) if __name__ == '__main__': print('当前mothe 进程: {}'.format(os.getpid())) start = time.time() for i in range(2): long_time_task() end = time.time() print('总共耗时: {}'.format(end - start)) # ➜ tmp py3 mul.py # 当前mothe 进程: 36016 # 当前里程id 36016 # 结果:1152921504606846976 # 当前里程id 36016 # 结果:1152921504606846976 # 总共耗时: 4.000534772872925 from multiprocessing import Process import time import os def long_time_task(i): print('子进程 {} - 任务{}'.format(os.getpid(),i)) time.sleep(2) print("结果:{}".format(8 ** 20)) if __name__ == '__main__': print('当前mothe 进程: {}'.format(os.getpid())) start = time.time() p1 = Process(target=long_time_task,args=(1,)) p2 = Process(target=long_time_task,args=(2,)) print('等所有子进程完成') p1.start() p2.start() p1.join() p2.join() end = time.time() print('总共耗时: {}'.format(end - start)) # ➜ tmp py3 mul2.py # 当前mothe 进程: 37124 # 等所有子进程完成 # 子进程 37126 - 任务1 # 子进程 37127 - 任务2 # 结果:1152921504606846976 # 结果:1152921504606846976 # 总共耗时: 2.0068671703338623 #AI解说不错 # 创建子进程 # p1 = Process(target=long_time_task,args=(1,))和p2 = Process(target=long_time_task,args=(2,)) # 这里使用Process类(假设是multiprocessing模块中的Process类)创建了两个子进程。 # target参数指定了子进程要执行的函数,这里是long_time_task函数。 # args参数是一个元组,指定了传递给long_time_task函数的参数,这里分别传递了1和2作为任务编号相关的参数。 # 启动和等待子进程 # p1.start()和p2.start()分别启动两个子进程,使它们开始执行long_time_task函数。 # p1.join()和p2.join()使主进程等待两个子进程完成。join方法会阻塞主进程,直到对应的子进程执行完毕。 # 记录结束时间和打印总耗时 # end = time.time()记录当前时间,作为任务结束的时间点。 # print('总共耗时: {}'.format(end - start))计算并打印从任务开始到结束所花费的时间。 # 这段代码的主要目的是创建两个子进程,让它们并行执行long_time_task函数,然后等待子进程完成,并计算整个过程所花费的时间。
multiprocess模块的Pool类创建多进程
from multiprocessing import Pool,cpu_count import time import os def long_time_task(i): print('子进程 {} - 任务{}'.format(os.getpid(),i)) time.sleep(2) print("结果:{}".format(8 ** 20)) if __name__ == '__main__': print('cpu core num: {}'.format(cpu_count())) print('当前mothe 进程: {}'.format(os.getpid())) start = time.time() p = Pool(12) for i in range(5): p.apply_async(long_time_task,args=(i,)) print('等所有子进程完成') p.close() p.join() end = time.time() print('总共耗时: {}'.format(end - start)) # cpu core num: 12 # 当前mothe 进程: 40772 # 等所有子进程完成 # 子进程 40776 - 任务0 # 子进程 40777 - 任务1 # 子进程 40778 - 任务2 # 子进程 40779 - 任务3 # 子进程 40780 - 任务4 # 结果:1152921504606846976结果:1152921504606846976 # 结果:1152921504606846976 # 结果:1152921504606846976 # 结果:1152921504606846976 # 总共耗时: 2.0383548736572266
多进程间的数据共享与通信
from multiprocessing import Process, Queue import os, time, random # 写数据进程执行的代码: def write(q): print('Process to write: {}'.format(os.getpid())) for value in ['A', 'B', 'C']: print('Put %s to queue...' % value) q.put(value) time.sleep(random.random()) # 读数据进程执行的代码: def read(q): print('Process to read:{}'.format(os.getpid())) while True: value = q.get(True) print('Get %s from queue.' % value) if __name__=='__main__': # 父进程创建Queue,并传给各个子进程: q = Queue() pw = Process(target=write, args=(q,)) pr = Process(target=read, args=(q,)) # 启动子进程pw,写入: pw.start() # 启动子进程pr,读取: pr.start() # 等待pw结束: pw.join() # pr进程里是死循环,无法等待其结束,只能强行终止: pr.terminate() Process to write: 3036 Put A to queue... Process to read:9408 Get A from queue. Put B to queue... Get B from queue. Put C to queue... Get C from queue.
Python的多线程编程与threading模块
threading比较高级 不像thread 太底层,要做太多事 import threading import time def long_time_task(i): print('当前子线程: {} 任务{}'.format(threading.current_thread().name, i)) time.sleep(2) print("结果: {}".format(8 ** 20)) if __name__=='__main__': start = time.time() print('这是主线程:{}'.format(threading.current_thread().name)) thread_list = [] for i in range(1, 3): t = threading.Thread(target=long_time_task, args=(i, )) thread_list.append(t) for t in thread_list: t.start() for t in thread_list: t.join() end = time.time() print("总共用时{}秒".format((end - start))) 这是主线程:MainThread 当前子线程: Thread - 1 任务1 当前子线程: Thread - 2 任务2 结果: 1152921504606846976 结果: 1152921504606846976 总共用时2.0166890621185303秒 ➜ tmp py3 threading.py Traceback (most recent call last): File "/home/evan/data/python/tmp/threading.py", line 10, in <module> print('当前主线程 {}'.format(threading.current_thread().name)) ^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'threading' has no attribute 'current_thread' Exception ignored in: <module 'threading' from '/home/evan/data/python/tmp/threading.py'> AttributeError: module 'threading' has no attribute '_shutdown' ➜ tmp
import threading def say_hi(): print('Hello world') if __name__ == '__main__': for i in range(3): t = threading.Thread(target=say_hi) t.start() #启动工作线程 target() # Hello world # Hello world # Hello world import threading def say_hi(word): print('Hello %s' % world) if __name__ == '__main__': for i in range(3): t = threading.Thread(target=say_hi,args=('mydu',)) t.start() #启动工作线程 target() import subprocess import threading def ping(host): result = subprocess.run( 'ping -c2 %s &> /dev/null' % host, shell=True ) if result.returncode == 0: print('%s:up' % host) else: print('%s:down' % host) if __name__ == '__main__': ips = ['192.168.10.%s' % i for i in range(1,6)] for ip in ips: t = threading.Thread(target=ping,args=(ip,)) t.start() #oop 化 import subprocess import threading class Ping: def __call__(self,host): result = subprocess.run( 'ping -c2 %s &> /dev/null' % host, shell=True ) if result.returncode == 0: print('%s:up' % host) else: print('%s:down' % host) if __name__ == '__main__': ips = ['192.168.10.%s' % i for i in range(1,6)] for ip in ips: t = threading.Thread(target=Ping(),args=(ip,)) t.start() # target(*args) # 2 oop import subprocess import threading #绑定在实例上的属性 class Ping: def __init__(self,host): self.host = host def __call__(self): result = subprocess.run( 'ping -c2 %s &> /dev/null' % self.host, shell=True ) if result.returncode == 0: print('%s:up' % self.host) else: print('%s:down' % self.host) if __name__ == '__main__': ips = ['192.168.10.%s' % i for i in range(1,6)] for ip in ips: t = threading.Thread(target=Ping(ip)) t.start() # target()
类对象
#!/usr/bin/python3 class MyClass: """一个简单的类实例""" i = 12345 def f(self): return 'hello world' # 实例化类 x = MyClass() # 访问类的属性和方法 print("MyClass 类的属性 i 为:", x.i) print("MyClass 类的方法 f 输出为:", x.f()) # 以上创建了一个新的类实例并将该对象赋给局部变量 x,x 为空的对象。 执行以上程序输出结果为: MyClass 类的属性 i 为: 12345 MyClass 类的方法 f 输出为: hello world
see also
__init__() 的特殊方法(构造方法)
类有一个名为 __init__() 的特殊方法(构造方法),该方法在类实例化时会自动调用 #!/usr/bin/python3 class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) print(x.r, x.i) # 输出结果:3.0 -4.5