标签:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def mail(email, message): print("去发吧") return Truemail("alex3714@126.com","好人")面向对象:类,对象class Foo: def mail(self,email,message): print(‘去发吧‘) return True#调用1、创建对象,类名()obj = Foo()2、通过对象去执行方法obj.mail("alex3714@126.com","好人") |
1 2 3 4 5 6 7 8 9 10 | a. 创建类 class 类名: def 方法名(self,xxxx): passb. 创建对象 对象= 类名() c.通过对象执行方法 对象.方法名(123) |
1 2 3 4 5 6 7 8 | def fetch(host, username, password, sql): passdef create(host, username, password, sql): passdef remove(host, username, password, sql): passdef modify(host, username, password, sql): pass |
函数式编程可以看出,没定义一个功能,就需要输入一遍mysql的登录信息(user,host,pass等)
1 2 3 4 5 6 7 8 9 10 11 12 13 | class SQLHelper: def fetch(self, host, username, password, sql): pass def create(self, host, username, password, sql): pass def remove(self, host, username, password, sql): pass def modify(self, host, username, password, sql): pass obj = SQLHelper()obj.fetch() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class SQLHelper: def fetch(self, sql): pass def create(self, sql): pass def remove(self, sql): pass def modify(self, sql): pass obj = SQLHelper() obj.hhost = "c1.salt.com" #执行这个,可以在类中定义hhost = "c1.salt.com"obj.uusername = "alex" #同上obj.pwd = "123" #同上obj.fetch(......) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class SQLHelper: def fetch(self, sql): print(self.hhost, sql) print(self.uusername, sql) print(self.pwd, sql) def create(self, sql): pass def remove(self, sql): pass def modify(self, sql): passobj = SQLHelper()obj.hhost = "c1.salt.com"obj.uusername = "alex"obj.pwd = "123"obj.fetch("select biubiubiu")执行结果:c1.salt.com select biubiubiualex select biubiubiu123 select biubiubiu |
1 2 3 4 | obj2.fetch(‘select....‘) self=obj2obj1.fetch(‘select....‘) self=obj1 |
1 2 3 4 5 | class dididi(): def __init__(self): print("自动执行init") obj = dididi() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class SQLHelper: def __init__(self, a1, a2, a3): self.hhost = a1 self.uusername = a2 self.pwd = a3 def fetch(self, sql): pass def create(self, sql): pass def remove(self, sql): pass def modify(self, sql): passobj1 = SQLHelper(‘c1.salt.com‘, ‘didi‘, 123)obj1.fetch(‘select * from A‘) |
对象中封装对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class c1: def __init__(self, name, obj): self.name = name self.obj = objclass c2: def __init__(self, name, obj): self.name = name self.obj = obj def show(self): print(self.name)class c3: def __init__(self, money, a1): self.money = 123 self.aaa = a1c2_obj = c2(‘aa‘, 11)c1_obj = c1(‘bb‘, c2.obj)c1_obj.obj #此时c1_obj.obj 就是c2.obj的值c3_obj = c3(c1_obj)print(c3.aaa) |
标签:
原文地址:http://www.cnblogs.com/yangruizeng/p/5616113.html