python3 类相关

1、如何创建类
    class 类名:
        pass
        
2、创建方法
    构造方法,__init__(self,arg)
        obj = 类('a1')
    普通方法
        obj = 类(‘xxx’)
        obj.普通方法名()
        
3、面向对象三大特性之一:封装


    class Bar:
        def __init__(self, n,a):
            self.name = n
            self.age = a
            self.xue = 'o'
            
    b1 = Bar('alex', 123)
    
    b2 = Bar('eric', 456)
    
    
4、适用场景:
        如果多个函数中有一些相同参数时,转换成面向对象


    class DataBaseHelper:
    
        def __init__(self, ip, port, username, pwd):
            self.ip = ip
            self.port = port
            self.username = username
            self.pwd = pwd
        
        def add(self,content):
            # 利用self中封装的用户名、密码等   链接数据
            print('content')
            # 关闭数据链接
        
        def delete(self,content):
            # 利用self中封装的用户名、密码等   链接数据
            print('content')
            # 关闭数据链接
        
        def update(self,content):
            # 利用self中封装的用户名、密码等   链接数据
            print('content')
            # 关闭数据链接
            
        def get(self,content):
            # 利用self中封装的用户名、密码等   链接数据
            print('content')
            # 关闭数据链接


s1 = DataBaseHelper('1.1.1.1',3306, 'alex', 'sb')


5、面向对象三大特性之二:继承


    1、继承
        
        class 父类:
            pass
            
        class 子类(父类):
            pass
            
    2、重写
        防止执行父类中的方法
        
    3、self永远是执行改方法的调用者


    4、
       super(子类, self).父类中的方法(...)
       父类名.父类中的方法(self,...)
       
       
       
    5、Python中支持多继承


        a. 左侧优先
        b. 一条道走到黑
        c. 同一个根时,根最后执行
    
6、面向对象三大特性之三:多态
    ====> 原生多态
    
    # Java
        string v = 'alex'
        
        def func(string arg):
            print(arg)
            
        func('alex')
        func(123)
    
    # Python 
        v = 'alex'
        
        def func(arg):
            print(arg)
            
            
        func(1)
        func('alex')


    
 
==================================================================
    
练习:
    
    class Person:
        
        def __init__(self,n,a,g,f):
            
            self.name = n
            self.age =a 
            self.gender =g
            self.fight = f 


                
    role_list = []
    
    y_n = input('是否创建角色?')
    if y_n == 'y':
        name = input('请输入名称:')
        age = input('请输入名称:')
        ...
        role_list.append(Person(....))
        
    # role_list,1,2 
        
        
======================================================= 面向对象中高级 ========================================================




class Foo:


    def __init__(self, name):
        # 普通字段
        self.name = name


    # 普通方法
    def show(self):
        print(self.name)


obj = Foo('alex')
obj.name
obj.show()




类成员:
    # 字段
        - 普通字段,保存在对象中,执行只能通过对象访问
        - 静态字段,保存在类中,  执行 可以通过对象访问 也可以通过类访问
        
    # 方法
        - 普通方法,保存在类中,由对象来调用,self=》对象
        - 静态方法,保存在类中,由类直接调用
        -   类方法,保存在类中,由类直接调用,cls=》当前类


    ######## 应用场景:
        如果对象中需要保存一些值,执行某功能时,需要使用对象中的值 -> 普通方法
        不需要任何对象中的值,静态方法
        
        
    # 属性,特性
        - 不伦不类
        
    

    

class provence:
    #静态字段,属于类
    country = "中国"
    def __init__(self,name):
        #普通字段,属于对象
        self.name = name

    @staticmethod # 使用装饰器,得到静态方法,类可直调用
    def static_func():
        print("静态方法")
        return 1
    @classmethod   # classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。
    def classmd(cls): #cls是当前类
        print("1111222333_class_method")

    @property  #类似属性字段调用
    def func(self):
        print("@property装饰的方法类似属性字段调用")
        return self.name
    @func.setter  #设置func的值执行函数, hebei.func = "set the attribute"
    def func(self,value):
        print(value)

provence.static_func()
provence.classmd()
hebei = provence("河北")
print("property:",hebei.func)  # 属性字段方法调用不用括号 执行@property 装饰函数
hebei.func = "set the attribute"  #执行@func.setter 装饰的函数
print(hebei.static_func())
print(hebei.name,hebei.country)
print(provence.country)

#修改对象的字段
hebei.name = "河北省"
print(hebei.name)

#修改静态字段
provence.country="China"
print(provence.country) #修改静态字段
print(hebei.country)
henan = provence("河南")
print(henan.country)

  单例模式,实例化的一个对象

#创建单例模式的对象,即实例化的对像仅一个一直用
class foo:

    __v = None # 私有字段
    @classmethod  # classmethod修饰的方法不需要进行实例化, 进行创建单例模式对象
    def get_instance(cls):
        if cls.__v:
            return cls.__v
        else:
            cls.__v = foo()
            return cls.__v

#此处实例化的对象均为同一个
obj1 = foo.get_instance() 
print(obj1)
obj2 = foo.get_instance()
print(obj2)
obj3 = foo.get_instance()
print(obj3)


    
中国的所有省份,用面向对象知识表示?


class Province:
    # 静态字段,属于类
    country =  '中国'
    
    
    def __init__(self, name):
        # 普通字段,属于对象
        self.name = name
        
henan = Province('河南')
henan.name
henan.name = "河南南"




#hebei = Province('河北')

# Province.country

私有字段方法:

class bar:
    def __init__(self):
        self.name = "hello"
        self.__age = "World" # 私有变量,外部无法直接访问,通过构造函数访问
    def show(self): #构造函数的访问私有字段
        print(self.__age)

    def __func_show(self):
        print("父类的私有方法访问")

    def func_show(self): #构造函数间接调用私有函数
        self.__func_show()

class ch_bar(bar):
    def __init__(self,ge,go):
        self.ge = ge
        self.__go = go
        super(ch_bar,self).__init__() #执行父类的init

    def show(self):
        print(self.__go) #子类的私有字段
        print(self.name) #父类的共有字段
        super(ch_bar,self).show() #执行父类中的show方法
        # print(self.__age) #父类的私有字段,子类无法访问,私有字段只能在当前类中被访问

    def __func_show(self): #私有方法
        print(self.ge+'-'+self.__go)

    def func_show(self): #构造函数间接调用私有方法
        self.__func_show()

obj = ch_bar("python",'Class')
obj.show()
obj.func_show()
obj2 = bar()
obj2.func_show()
class foo:
    """
    类里面的特殊成员
    """
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __getitem__(self, item): # 对应对象后加[]的操作获取值
        return self.age
    def __setitem__(self, key, value):
        print("%s->%s"%(key,value))
    def __delitem__(self, key):
        print("delete:%s"%key)


lt = foo("QQ",10)
d= lt.__dict__  #获取对象中的成员变量,以字典形式返回
print(d)
r = lt[1]
print(r)
lt[5]="qwert" # 执lt对象中的__setitem__()方法,5当作参数传递给key,"qwert" 传给value
del lt[5] #执行lt对象中的__delitem__()方法
class f:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __iter__(self):
        s = iter([self.name,self.age])
        return s  #返回一个迭代对象
    n = 0 #静态字段
    def __next__(self):
        n = f.n #静态字段赋值
        l = [self.name,self.age]
        value = l[n]
        f.n += 1
        return  value

foo = f('zhansan',12)
print(next(foo))
print(next(foo))
for i in foo:
    print(i)
class ch_type(type): # python的type类作为父类,ch_type继承type类
    def __init__(self,*args,**kwargs):
        print("123")
        pass

class foo(object,metaclass=ch_type): #新建类对象,ch_type类作为祖类
    def __init__(self):
        pass
    def func(self):
        print("hello metaclass")

    def __call__(self, *args, **kwargs):  # __call__()方法对象加括号调用call方法
        print("foo()()直接调用__call__()函数")

obj= foo() #创建对象obj,执行foo的__init__()函数
obj()   #对象加() 执行foo中的__call__()函数

异常捕获处理

try:
    l=[1,2,3]
    x= l[4]
    int("qwer")
except ValueError as e:  #抛出异常ValueError
    print("ERROR:",e)
except Exception as e:  #抛出任何异常 按代码执行顺序从上往下,有特定的error就直接抛出
    print("Error:",e)
finally:
    print("finally执行")


#自定义异常类
class BadError(Exception): #从Exception继承
    def __init__(self,message):
        self.msg = message

    def __str__(self):
        return self.msg

import time
nowtime = time.localtime()
t = time.strftime("%Y-%m-%d %H:%M:%S",nowtime)
try:
    raise BadError("报错了") #主动触发异常
except BadError as  e: #写入到log文件
    error = str(e)
    with open ("log.f1",'a',encoding="utf-8") as f: 
        f.write(t+error+"\n")

assert 断言抛出异常

#assert 断言,条件不满足就直接报错, 可以捕获,一般不用捕获
assert  1==2 #条件不满足 直接报错,程序停止继续执行
print("123")

反射

class foo:

    def __init__(self,name,age):
        self.name = name
        self.age = age
    def show(self):
        return "%s->%s"%(self.name,self.age)

obj = foo("Jim",18)
# print(obj.name)
# b = "name"
# print(obj.b) # AttributeError: 'foo' object has no attribute 'b'
b = "name"
print(obj.__dict__[b])  # obj.__dict__ 将对象的字段属性转换为字典,拿到对象的字段
print(obj.__getattribute__(b))  #通过__getattribute__()获取字段的值,b="name"作为字段名
value = getattr(obj,b)  #getattr()方法获取字段值
print(value)
#用getattr()方法获取类里面的方法
func = getattr(obj,"show")
print(func)
ret = func()
print(ret)
#用hasattr()方法判断类中是否有某个字段或者方法
print(hasattr(obj,"show")) #返回True
print(hasattr(obj,b))

#setattr()方法设置属性或者方法
setattr(obj,"key","value")  # 设置后字段名和值存在对象的内存空间中
print(hasattr(obj,"key")) # 返回True
print(getattr(obj,"key")) #返回Value
#deleattr() 删除字段
delattr(obj,"key") #删除key字段名
print(hasattr(obj,"key")) #返回False
getattr(obj,"key")  # AttributeError: 'foo' object has no attribute 'key'

 利用反射做一些事情,获取其他的模块的函数功能或者变量字段值等

#tests.py模块
class foo:

    def show1(self):
        print("首页")

    def show2(self):
        print("博客")

    def show3(self):
        print("下载")

#反射方式访问执行tests.py中的功能
import tests
obj = tests.foo() #tests中的类创建对象
while True:
    inp = input (">>:") #输入show1/show2/show3
    if hasattr(obj,inp):
        func = getattr(obj,inp) #获取方法
        func() #执行对应的方法
    else:
        print("Not Found")

猜你喜欢

转载自blog.csdn.net/dance117/article/details/80973658