温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python面向对象的操作方法

发布时间:2022-03-29 15:50:44 来源:亿速云 阅读:110 作者:iii 栏目:移动开发

这篇文章主要介绍了python面向对象的操作方法的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇python面向对象的操作方法文章都会有所收获,下面我们一起来看看吧。

操作Redis集群:

import rediscluster
import redis
# startup_nodes = [
#     {"host":"118.24.3.40","password":"HK139bc&*","port":6379},
#     {"host":"118.24.3.41","password":"HK139bc&*","port":6379}
#                  ]
# r = rediscluster.RedisCluster(startup_nodes =startup_nodes, decode_responses=True)
# print(r.keys())

r = redis.Redis(host="118.24.3.40",password="HK139bc&*",port=6379,db=4,decode_responses=True)
r.set("ljq:ljq1","ljj") #文件夹ljq,key:ljq1
print(r.get("ljq:ljq1")) #取值时要把文件夹带上

面向对象:

# class Car:
#     wheel = 4
#     color = "heise"
#     name = "feimaqiche"
#     def fly(self):
#         print(self.name)
#
# fmz_car = Car()#实例化        fmz_car:实例对象
# fmz_car.fly()#调用类里面的方法
#self 本类对象,实例化的是谁,self代表的是谁

class Car:
    wheel = 4  #类变量,公共的,通过self.wheel来应用
    def __init__(self,color,name): #构造函数,类在实例化的时候,自动执行的函数
        self.color = color
        self.name = name

    def __del__(self):#析构函数,实例在销毁的时候执行
        print("析构函数")

    def fly(self):
        name= "www"#局部变量
        print(id(self))
        print(self.name)

    def say(self):
        print("%s,%s"%(self.name,self.color))


fmz_car = Car("红色的","汽车")#实例化        fmz_car:实例对象
fmz_car.fly()#调用类里面的方法
fmz_car.say()#调用类里面的方法
print(id(fmz_car))

fmz_car2 = Car("黄色的","汽车")#实例化        fmz_car:实例对象
fmz_car2.fly()#调用类里面的方法
fmz_car2.say()#调用类里面的方法

#raise 主动抛出异常
# 私有方法,私有变量, :前面加 __  类里可以调用,出了类之后就不能调用

封装MySQL类:

import pymysql
from day8li.homework.const import mysql_info
class MySQL: #经典类

    def __init__(self,mysql_info,data_type=1):
        self.mysql_info = mysql_info
        self.data_type = data_type
        self.__connect_status = False
        self.__connect()

    def __connect(self):
        print("开始连接mysql")
        try:
            self.__conn = pymysql.connect(**self.mysql_info)
        except:
            print("数据库连接出错!" )
            raise Exception("数据库连接出错")
        self.__connect_status = True
        if self.data_type != 1:
            self.__cur = self.__conn.cursor(pymysql.cursors.DictCursor)
        else:
            self.__cur = self.__conn.cursor()
        print("mysql连接成功!")

    def execute(self,sql):
        print("开始执行sql",sql)
        try:
            self.__cur.execute(sql)
        except:
            print("sql不正确,sql语句是%s" % sql)
        else:
            print("sql执行完成!")
            return True

    def fetchone(self,sql):
        if self.execute(sql):
            return self.__cur.fetchone()

    def fetchall(self,sql):
        if self.execute(sql):
            return self.__cur.fetchall()

    def __del__(self):
        self.__close()
        print("mysql 连接关闭完成")

    def __close(self):
        if self.__connect_status:
            self.__cur.close()
            self.__conn.close()



if __name__ == '__main__':
    my = MySQL(mysql_info)
    my.execute("update user_nhy_7 set nick ='杜拉拉' where id = 3")

    ret = my.fetchone("select * from user_nhy_7 where id = 3")
    print(ret)
    ret = my.fetchall("select * from user_nhy_7")
    print(ret)

日志打印:

# import logging
# log = logging.Logger("abc",level="INFO")
# log.info("haha")

# import loguru
# loguru.logger.debug("aaa")
# loguru.logger.info("aaa")
# loguru.logger.warning("aaa")
# loguru.logger.error("aaa")


from loguru import logger
import sys
logger.remove()  # 清除它的默认设置设置
# fmt = '{time}||{level}||{file.path}:line:{line}:function_name:{function} ||msg={message}'
fmt = '{time}||msg={message}'
# level file function module time message
# logger.add(sys.stdout, level='DEBUG', format=fmt)  # 咱们本地运行的时候,在控制台打印
# #  enqueue=True  异步写入日志
# logger.add('fmz.log', level='DEBUG', format=fmt, encoding='utf-8',
#            enqueue=True, rotation='1 day', # rotation多久产生一个日志文件
#            retention='10 days')  # 写在日志文件里面
#
# logger.info("3253252")



class Log:
    logger.remove()#清除它的默认设置设置
    fmt = '[{time}][{level}][{file.path}:line:{line}:function_name:{function}] ||msg={message}'
    #level file function module time message
    logger.add(sys.stdout,level="DEBUG",format=fmt)#咱们本地运行的时候,在控制台打印
    logger.add("test.log",level="DEBUG",format=fmt,encoding='utf-8',enqueue=True,rotation='1 day',retention='10 days')#写在日志文件里面

    debug = logger.debug
    info = logger.info
    warning = logger.warning
    error = logger.error

if __name__ == '__main__':
    Log.info("xxxx")

关于“python面向对象的操作方法”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“python面向对象的操作方法”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI