在java,c#语言中只能使用面向对象式编程,python中当某一些函数具有相同参数时,可以使用面向对象式编程,将参数一次性封装到对象,以后去对象中取就可以
class f1: def __init__(self,a1,b1,c1): self.a1 = a1 self.a2 = b1 self.a3 = c1 def select(self,sql): print(self.a1,self.a2,self.a3,sql) def add(self,sql): print(sql) #实例化的时候自动执行类的__init__构造方法 obj = f1(‘1‘,‘2‘,‘3‘) obj.host = ‘abc.com‘ obj.username = ‘alex‘ obj.pwd = ‘123‘ #当某些函数拥有相同参数时,使用面向对象 obj.select(‘select * from A‘) obj.add(‘create table from A‘) >>>1 2 3 select * from A >>>create table from A
1 class c1: 2 def __init__(self,name,obj): 3 self.name = name 4 self.obj = obj 5 6 class c2: 7 def __init__(self,name,age): 8 self.name = name 9 self.age = age 10 def show(self): 11 print(self.name) 12 13 c2_obj = c2(‘bb‘,18) 14 #将c2_obj当作参数传入obj,则c1_obj.obj=c2_obj c2_obj.show = c1_obj.obj.show() 15 c1_obj = c1(‘aa‘,c2_obj) 16 c1_obj.obj.show() 17 >>>bb
1 class F1:#父类,基类 2 def show(self): 3 print(‘show‘) 4 def foo(self): 5 print(self.name) 6 7 class F2(F1):#子类,派生类 8 def __init__(self,name): 9 self.name = name 10 def bar(self): 11 print(‘bar‘) 12 def show(self): 13 print(‘F2.show‘) 14 #继承相当于将F1的方法放到F2中, 15 obj = F2(‘alex‘) 16 obj.foo() 17 #两个类中有相同方法时,自身的方法优先级高 18 obj.show() 19 >>>alex 20 >>>F2.show
1 class f1(): 2 def c1(self): 3 print(‘c1‘) 4 class f2(f1): 5 def c2(self): 6 print(‘c2‘) 7 class f3(f2): 8 def c3(self): 9 print(‘c3‘) 10 11 class f5(): 12 def c2(self): 13 print(‘c5‘) 14 class f4(f3,f5): 15 def c4(self): 16 print(‘c4‘) 17 #当子类有两个类时,优先从左边分支寻找,左边分支找到头之后找右边 18 obj =f4() 19 obj.c2()
>>>c2
原文:http://www.cnblogs.com/liguangxu/p/5605314.html