Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Time : 2018/11/14 22:17
- # Author : Jenson
- def sayHello(name): #正常地定义函数
- print("{0}你好,来一发吗?".format(name))
- sayHello("月月") # “月月”作为参数传入到函数sayHello
- liumang = sayHello # 将函数名sayHello赋值给变量liumang,此时liumang和sayHello已经等价
- liumang("月月")
- class A():
- pass
- def say(self):
- print("Saying...")
- class B():
- def work(self):
- print("Working...")
- print(say(9)) # 9作为一个参数传进函数say(),运行并打印结果
- A.say = say #函数名称say赋值给变量A.say
- a = A() #实例化a
- print(a.say()) #对象a调用函数say,运行并打印结果
- b = B() #实例化b
- b.work() #对象b调用函数
- print("*"*200)
- """
- 利用MethodType创建类
- """
- from types import MethodType
- class C():
- pass
- def say1(self):
- print("Saying...") #程序运行到此,类class和函数say1还没有任何关系
- c = C()
- c.say1 = MethodType(say1, C) # MethodType()方法将类class和函数say1绑一块了 MethodType()有两个参数,C是函数say1绑定的类
- print(c.say1())
- print("*"*200)
- """
- 利用Type造一个类
- """
- def say2(self): #先定义类应该具有的成员函数
- print("Saying...")
- def talk(self): #先定义类应该具有的成员函数
- print("Talking...")
- A =type("Aname", (object, ), {"class_say":say2, "class_say":talk}) #用type创建一个类
- #第一个参数,类名
- #第二个参数,有所有的父类组成的一个tuple
- #第三个参数,一个字典类型的参数
- a = A()
- print(dir(a))
- print("*"*200)
Add Comment
Please, Sign In to add comment