参考地址:https://www.cnblogs.com/wupeiqi/p/4766801.html

类的创建和方法

1、如何创建类
    class 类名:
        pass

2、创建方法:构造方法和普通方法
    构造方法:创建对象时自动执行该方法
        __init__(self, args)#自带构造方法,也可以重写该方法。self是指实例化对象。
        obj = 类("alex")#实例化一个对象则调用类的构造方法__init__(),并传参args=alex
    普通方法:需要主动调用执行该方法
        obj = 类("alex")#实例化类对象,并给构造方法传参
        obj.普通方法名()#普通方法需要通过实例对象加点号调用方法名

******************************* 类的封装 *********************************************
1、面向对象三大特性之一:封装,即将数据存储在对象内
    class Bar:
        def __init__(self, n, a):#重写构造方法时的第一个参数必须是self
            self.name = n
            self.age = a
            self.type = 'o'
    b1 = Bar("alex", 123)#实例化对象b1,同传参给构造方法
    b2 = Bar("eric", 456)#实例化对象b2,同传参给构造方法
    
2、适用场景:如果多个函数中有一些相同参数时,转换成面向对象
    class DataBaseHelper:
        def __init__(self, ip, port, usernmae, password):
            self.ip = ip
            self.port = port
            self.username = username
            self.password = password
        
        def add(self, content):
            #利用self中封装的用户名密码等信息进行操作数据库
            print("add")
        def del(self, content):
            #利用self中封装的用户名密码等信息进行操作数据库
            print("del")
    s1 = DataBaseHelper("1.1.1.1", 3306, "alex", "sb")#实例化对象并传参                                                                                                                                                    
                                                                                                                                                                                                                                                                                              
******************************* 类的继承 *********************************************
1、面向对象三大特性之二:继承
class Father:#创建father类
    def f1():
        print('f1')
class Son(Father):创建Son类,同时集成Father类
    def f2():
        super(Son,self).f1()#调用父类方法一,常用
        Father.f1.(self)#调用父类方法二,调用父类方法第一个参数必须为self
        print('f2')     
                                                                                                                                                                                                                                                                                                                                                                                                                                          
2、重写
    子类重写了父类的方法,子类调用该方法时就是调用的子类重写的方法,不去调用父类方法                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
3、self是指类的实例化对象,该对象无聊调用自身方法还是父类方法,self都代表该对象
4、调用被重写的父 类方法,两种方式:
    4.1 super(子类名、self).父类方法()
    4.2 父类名.父类的方法(self,。。。)  
     
5、多继承
class grandfather:
    def a(self):
        print('grandfather')
class father:
    def a(self):
        print('father')
   
class son(father, grandfather):
#father类先于grandfather类,调用父类方法先去father类查找
    pass
obj = son()
obj.a()#  输出“father”,因为son类继承是以顺序优先的,father高于grandfather,优先调用father中的方法
【注意】:
    》多
继承中,如果各个父类独立没有公共基类,则调用父类方法时依次按继承顺序查找            
    》多继承中,如果被继承的两个类中有公共的基类,则在查找基类中的方法之前,会按继承顺序依次调用被调用的类中的方法,最后在调用公共基类的方法。
    
》在继承的父类中,通过self方法调用其他方法时,查询该方法也必须按继承顺序区查找,不受父类环境影响。

 

类的继承

1、面向对象三大特性之三:多态
    age = ’18’
    age = 18
2、多态是指变量或参数可接受不同类型的数据,Python原生支持多态。

 

类的静态资源

1、类的静态变量

class Son:
    name = "alex"//类中创建静态变量
    def cando(self, age):
        self.age = age//对象中创建普通变量
    1、字段中普通变量保存在对象中,执行时只能通过对象访问
    2、字段中静态变量保存在类中,执行时即可通过类来访问,也可以通过对象来访问

 

2、类的静态方法

1、静态方法
class Son:
    @staticmethod
#类型静态方法必须加 @staticmethod 装饰器生命
    def cando(age):
#定义静态方法时,self参数是可选的,与函数相似
        print(age)
Son.cando(18)#静态方法可通过类名直接调用
,也可以通过对象调用
    1、类中的普通方法保存在对象中,执行时只能通过对象访问
    2、类中的静态方法保存在类中,执行时即可通过类来访问,也可以通过对象来访问

 

3、类方法

class son():
    @classmethod 
#加 @classmethod 装饰器表示是类方法
    def cando(cls):
#类方法必须得传一个参数,通常默认传cls,即class简写,这样调用就不必在创建对象在传参了,可以有类直接调用
        print("classmethod")
son.cando()
    1、类方法保存在类中,执行时即可通过类来访问,也可以通过对象来访问
,类方法与静态方法功能近似

 

4、类的装饰器属性:方法绑定

1、@property装饰器
class son():
    @property 
#加上 @property 装饰器后,调用该方法时以字段形式调用
    def cando(self):
        print("property ")
        return 2
son.cando #加了 @property 装饰器,只能以字段的形式来调用,不能以函数形式调用,即对象的属性

2、@property、@setter、@deleter装饰器
class Son:
    @property
    def cando(self):
#添加@property
装饰器后,对象调用obj.cando即调用本方法
        print('property')
    @cando.setter
#添加@cando.setter装饰器后,对象调用obj.cando=123即调用本方法
    def cando(self,var):
        print('setter',var)
    @cando.deleter

#添加@cando.deleter装饰器后,对象调用del obj.cando即调用本方法
    def cando(self):
        print('deleter')
obj = Son()
obj.cando#输出property
obj.cando=123
#输出setter 123
del obj.cando#输出deleter

3、property的fget/fset/fdel方法
class Son:
    def cando1(self):
        print('property')
    def cando2(self,var):
        print('setter',var)
    def cando3(self):
        print('deleter')
    cando = property(fget=cando1,fset=cando2,fdel=cando3)
obj = Son()
obj.cando
#调用cando1方法
obj.cando=123

#调用cando2方法
del obj.cando
#调用cando3方法

 

类的私有成员和方法

1、私有成员和私有方法修饰符(双下划线):__

class Farther:
    def __init__(self):
        self.__fname = 'farther'
#父类中的私有程序,子类也无权访问

class Son:
    __stName = 'Mark'
#定义子类的静态私有成员,只能通过类的方法间接访问
    def __init__(self, name, age):
        self.name = name
#定义类的普通成员
        self.__age = age
#定义类的普通私有成员
        super(Son,self).__init__()
#调用父类的方法
    def show(self):
        print(self.name)
#子类方法调用类的普通成员
        print(self.__fname)
#子类方法调用父类的私有成员,报错,无权调用
        return self.__age
#子类私有成员只能通过类的方法调用
obj = Son('alex', 18)
print(obj.show())

 

2、类的特殊方法

1、__init__:类创建对象时自动执行
该方法
2、__del__ :类的析构方法,不需要该对象时可以调用该方法去清理对象,也可以依赖系统清理
3、__call__:对象加括号,或类()(),自动执行该方法
    class Son:
        def __call__(self, *args, **kwargs):
            print('call')
    obj = Son()
#创建类对象
    obj()#对象加括号,调用类的__call__方法,绑定用法
4、__int__:其他对象转换为int时,即int(obj)时,int会调用obj的__int__方法
5、__str__:其他对象转换为str时,即str(obj)或print(obj)时,str会调用obj的__str__方法
6、__add__:两个对象相加,即调用第一个对象的__add__(self,obj2)方法,需要自己实现第一个对象的 __add__方法
的逻辑
7、__dict__:将对象中封装的所有内容通过字典的形式返回 
     class Son:
        __stName = 'Mark'
        def __init__(self, name, age):
            self.name = name
            self.__age = age
    obj = Son('alex',19)
    print(obj.__dict__)#可以输出对象的公有私有成员{'name': 'alex', '_Son__age': 19},类的静态私有成员不能输出
    print(Son.__dict__)
#可以输出类的成员信息{'__module__': '__main__', '_Son__stName': 'Mark', '__init__': <function Son.__init__ at 0x000002CEF22FFB80>, '__dict__': <attribute '__dict__' of 'Son' objects>, '__weakref__': <attribute '__weakref__' of 'Son' objects>, '__doc__': None}

8、列表和类的取值、赋值、删值方法:
__getitem__(self,item):相当于取list的第item个元素,即val = list[item]
,
__setitem__(self,key,value):相当于对list的第key个元素赋值value,即list[key] = value
__delitem__(self,item):相当删除list的第item个元素,即del list[item]
    class Son:
        def __getitem__(self, item):
            print(item)
        def __setitem__(self, key, value):
            print(key,value)
        def __delitem__(self, key):
            print(key)
    obj = Son()
    v = obj[2:6:2]
#类的实例化对象进行切片取值,即调用该类的__getitem__方法,必须先定义后调用
    v = obj[2]
#输出2;  类的实例化对象进行取值,即调用该类的__getitem__方法,必须先定义后调用
    obj[3] = 4
#输出3 4;类的实例化对象进行赋值,即调用该类的__setitem__方法,必须先定义后调用
    del obj[5]#输出5;  类的实例化对象进行删值,即调用该类的__delitem__方法,必须先定义后调用
9、__iter__(self):类的迭代方法
    class Son:
        def __iter__(self):
#必须先实现该方法,才可以对类的实例化对象进行迭代操作
            return iter([1,2,3,4])
#返回迭代器
    obj = Son()
    for i in obj:
#对实例化对象进行迭代操作,调用其迭代器
        print(i)

三、metaclass,类的祖宗

a、Python中一切事物都是对象
b、
    class Foo:
        pass
    obj = Foo()#obj是Foo类的实例化对象,Foo也是一个对象,默认是type的实例化对象
c、
    class myType:
        def __init__():
            print("123")
        def __call__():
            print("3445")    
    class Foo(metaclass=myType):#修改Foo默认的创建类,Foo是myType的类的对象
        pass#定义Foo类(即myType的对象)前,先执行myType类中的init和call方法

 

posted @ 2022-11-17 22:29  大碗麻辣烫  阅读(108)  评论(0)    收藏  举报