Guest User

Untitled

a guest
Nov 14th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Time : 2018/11/14 22:17
  4. # Author : Jenson
  5. def sayHello(name): #正常地定义函数
  6. print("{0}你好,来一发吗?".format(name))
  7. sayHello("月月") # “月月”作为参数传入到函数sayHello
  8. liumang = sayHello # 将函数名sayHello赋值给变量liumang,此时liumang和sayHello已经等价
  9. liumang("月月")
  10.  
  11. class A():
  12. pass
  13. def say(self):
  14. print("Saying...")
  15.  
  16. class B():
  17. def work(self):
  18. print("Working...")
  19. print(say(9)) # 9作为一个参数传进函数say(),运行并打印结果
  20. A.say = say #函数名称say赋值给变量A.say
  21. a = A() #实例化a
  22. print(a.say()) #对象a调用函数say,运行并打印结果
  23. b = B() #实例化b
  24. b.work() #对象b调用函数
  25.  
  26. print("*"*200)
  27.  
  28. """
  29. 利用MethodType创建类
  30. """
  31. from types import MethodType
  32. class C():
  33. pass
  34. def say1(self):
  35. print("Saying...") #程序运行到此,类class和函数say1还没有任何关系
  36. c = C()
  37. c.say1 = MethodType(say1, C) # MethodType()方法将类class和函数say1绑一块了 MethodType()有两个参数,C是函数say1绑定的类
  38. print(c.say1())
  39.  
  40. print("*"*200)
  41.  
  42. """
  43. 利用Type造一个类
  44. """
  45. def say2(self): #先定义类应该具有的成员函数
  46. print("Saying...")
  47. def talk(self): #先定义类应该具有的成员函数
  48. print("Talking...")
  49. A =type("Aname", (object, ), {"class_say":say2, "class_say":talk}) #用type创建一个类
  50. #第一个参数,类名
  51. #第二个参数,有所有的父类组成的一个tuple
  52. #第三个参数,一个字典类型的参数
  53. a = A()
  54. print(dir(a))
  55.  
  56. print("*"*200)
Add Comment
Please, Sign In to add comment