首页 > 代码库 > Python面向对象编程基础

Python面向对象编程基础

面向对象关键词:类,对象,实例,方法

面向对象三大特性:封装,继承,多态

class Foo:      # 定义类名
    def f1(self):     # f1方法
        print("success")


obj = Foo()    # 创建对象
obj.f1()          # 通过对象执行方法

类和对象的关系:

技术分享

 

self参数是一个Python自动会传值的参数,那个对象执行方法,self就是那个

class SQLhelp():

    def __init__(self, a1, a2, a3):         # 此方法会自动执行,那个对象执行的方法,self就是那个
        print("自动执行init")
        self.host = a1
        self.name = a2
        self.pwd = a3

    def find(self):
        pass


obj1 = SQLhelp(‘c1.salt.com‘, ‘djc‘, ‘100‘)    # 参数分别对应a1,a2,a3
print(obj1.host)

>>>
自动执行
c1.salt.com

  

 对象中封装对象

 

class c1:
    def __init__(self, name, obj):
        self.name = name
        self.obj = obj

class c2:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def show(self):
        print("MDZZ")

class c3:
    def __init__(self, a1):
        self.aaa = a1


c2_obj = c2("djc", 19)    # 要写在c1类之前
c1_obj = c1("sb", c2_obj)
ret = c1_obj.obj.name
print(ret)

>>>djc

c3_obj = c3(c1_obj)
ret2 = c3_obj.aaa.obj.show()
print(ret2)

>>>MDZZ

  

 技术分享

 

 简单单继承

# 继承相当于把父类的方法复制到了子类,而不是去父类里拿

class f1: # 父类,基类 def show(self): print("f1") def foo(self): print(self.name) class f2(f1): # 子类,派生类 def __init__(self, name) self.name = name obj = f2("djc") obj.foo() >>>djc

  

复杂单继承

class f1:
    def F1(self):
        self.F2()                # 执行f2的F2

    def F2(self):
        print("f1,F2")

class f2(f1):
    def F3(self):         
        self.F1()                 # 执行f1的F1

    def F2(self):
        print("f2,F2")

obj = f2()
obj.F3()       # 自己的方法优先,作为子类不要忽略继承的父类的方法,如果自己没有,才去父类里面找

>>>
f2,F2

技术分享

 

简单多继承

class c1:
    def f2(self):
        print("c1")

class c2:
    def f2(self):
        print("c2")

class c3(c2,c1):         # 左边的优先
    def f3(self):
        pass

obj = c3()
obj.f2()

>>>c2

稍复杂多继承

class c0:
    def f2(self):
        print("c0")

class c1:
    def f2(self):
        print("c1")

class c2(c0):
    def f1(self):
        print("c2")

class c3(c2,c1):
    def f3(self):
        pass

obj = c3()
obj.f2()

>>>c0

  技术分享

 

复杂多继承

 

class c_2:
    def f2(self):
        print("c_2")

class c_1(c_2):
    def f2(self):
        print("c_1")

class c0(c_2):
    def f1(self):
        print("c0")

class c1(c_1):
    def f1(self):
        print("c1")

class c2(c0):
    def f1(self):
        print("c2")

class c3(c2,c1):
    def f3(self):
        pass

obj = c3()
obj.f2()

>>>c-1

技术分享

 

 

 

class h5:
    def forever(self):
        self.run()

class h4(h5):
    def __init__(self):
        pass

    def run(self):
        self.process()

    def process(self):
        print("h4")

class h3(h4):
    def __init__(self):
        pass

class h2:
    def process(self):
        print("h2")

class A(h2, h3):
    pass

obj = A()
obj.forever()

>>>h2

 技术分享

 

  

 

Python面向对象编程基础