# encoding='utf8'# auth:yanxiatingyu#2018.7.24

import pymysql

__all__ = ['Mymysql']

class MyExcept(Exception):    '''    常见做法定义异常基类,然后在派生不同类型的异常    '''

    def __init__(self, *args):        self.args = args

class DropDataaseError(MyExcept):    def __init__(self):        self.args = ('删除数据库错误!',)        self.message = '删除数据库错误!'        self.code = 100

class DropTableError(MyExcept):    def __init__(self):        self.args = ('删除表错误!',)        self.message = '删除表错误!'        self.code = 200

class CreateDatabaseError(MyExcept):    def __init__(self):        self.args = ('不能创建数据库',)        self.message = '不能创建数据库'        self.code = 300

class OperatorError(MyExcept):    '''    操作错误,一般是要做的事情和实际功能不匹配    '''

    def __init__(self, message):        self.args = (message,)        self.message = message        self.code = 400

class FileIsExistsError(MyExcept):    def __init__(self, message):        self.args = (message,)        self.message = message        self.code = 500

class Mymysql:    host = None    port = None    user = None    passpwd = None    database = None    charset = None

    conn = None    cursor = None

    @classmethod    def config(cls, db, host='localhost', port=3306, user='root', pwd='',               charset='utf8'):        cls.host = host        cls.port = port        cls.user = user        cls.passpwd = pwd        cls.database = db        cls.charset = charset        cls.__init_connect()        cls.__new_course()

    @classmethod    def __init_connect(cls):        cls.conn = pymysql.connect(            host=cls.host,            port=cls.port,            user=cls.user,            password=cls.passpwd,            database=cls.database,            charset=cls.charset        )

    @classmethod    def __new_course(cls):        cls.cursor = cls.conn.cursor()

    ## userinfo=[    #     (3,"alex"),    #     (4,"lxx"),    #     (5,"yxx")    #    # sql='insert into student values(%s,%s,%s);'    # cursor.executemany(sql,userinfo)    @classmethod    def filter(cls, sql):        '''        过滤sql语句        :param sql:        :return: 返回过滤后的sql语句        '''

        return sql.lower()

    # @multimethod    # def __query(cls, sql):    #     msg = 0    #     try:    #         msg = cls.cursor.execute(cls.filter(sql))    #         cls.conn.commit()    #     except Exception as e:    #         cls.conn.rollback()    #     finally:    #         return msg

    @classmethod    def __query(cls, sql,*args):        '''        底层查询        :param sql:        :param args:        :return: rows 操作成功返回受影响的行数        '''        rows = 0        try:            rows = cls.cursor.execute(cls.filter(sql), *args)            cls.conn.commit()        except Exception as e:            cls.conn.rollback()        finally:            return rows

    @classmethod    def insert(cls, sql, args):        if not ('insert into' in sql.lower()):            raise OperatorError('这是插入操作!')        return cls.__query(sql, args)

    @classmethod    def update(cls, sql):  # update test set name='你好'  where name='egon';        if not ('update' in sql.lower()):            raise OperatorError('这是更新操作')        return cls.__query(sql)

    @classmethod    def drop(cls, sql):

        if not ('drop' in sql.lower()):  # drop table test;            raise OperatorError('无法提供非drop table类的方法')

        if not ('drop database' in sql):            raise OperatorError('无法删除数据库!')

        return cls.__query(sql)

    @classmethod    def delete(cls, sql):        if not ('delete ' in sql.lower()):            raise OperatorError('无法提供非delete 记录操作!')        return cls.__query(sql)

    # 记录级别    # alter table test add age int;    # alter table test modify name char(15);    # alter table test change  NAME char(15);#    # alter table test drop age;    @classmethod    def alter(cls, sql):        if not ('alter' in sql.lower()):            raise OperatorError('只能提供修改操作')

        if not ('alter database' in sql):            raise OperatorError('操作错误你大爷')

        return cls.__query(cls)

    @classmethod    def create(cls, sql):        if not ('create database' in sql.lower()):            raise OperatorError('不准创库操作')

        if not ('create table' in sql):            raise OperatorError('操作错误')

        return cls.__query(sql)

    @classmethod    def truncate(cls, table_name):        table_name = table_name.strip()        if not isinstance(table_name, str):            raise TypeError('类型错误')        return cls.__query('truncate %s;' % table_name)

    # update test set name='lxx_dsb' where id=2;    # update yanxiatingyu  set name='lxx_dsb' where name='lxx';    @classmethod    def update(cls, sql):        if not ('update' in sql):            raise TypeError('只能更新')        return cls.__query(sql)

    @classmethod    def select(cls, sql):        if not ('select' in sql.lower()):            raise OperatorError('操作错误')        return cls.__query(sql)

    @classmethod    def get_line(cls, sql):        '''        获取单行的数据        :return:        '''        if not ('select' in sql):            raise OperatorError('执行查询')

        cls.__query(sql)

        try:            return True, cls.cursor.fetchone()        except:            return False, '没有数据'

    @classmethod    def get_lines(cls, sql):        '''        返回多行数据        :return:        '''        sql = sql.lower()

        if not ('select' in sql):            raise OperatorError('执行查询')        # print(sql.lower())        cls.__query(sql)        try:            return True, cls.cursor.fetchall()        except Exception as e:            print(e)            return False, '没有数据'

    @classmethod    def get_fetchmany(cls, sql, size=1):        '''        获取指定数量数据        :param size: 接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数        :return:tuple        '''        if not isinstance(size, int):            raise TypeError('类型错误')

        if size <= 0:            return None

        sql = sql.lower()        if not ('select' in sql):            raise OperatorError('执行查询')

        cls.__query(sql)

        return cls.cursor.fechmany(size)

    @classmethod    def close(cls):        '''        关闭cursor 和db 连接        :return:        '''        cls.cursor.close()        cls.conn.close()

Mymysql.config(db='db1')res = Mymysql.get_lines('select * from student;')print(res)

#config 
if mode:    if not os.path.exists(path):        raise FileIsExistsError('文件不存在')

    with open(path, 'rt', encoding='utf8') as f:        config_json_dic = json.load(f)

    cls.host = config_json_dic['host']    cls.port = config_json_dic['port']    cls.user = config_json_dic['user']    cls.passwd = config_json_dic['passwd']    cls.charset = config_json_dic['charset']

python 不需要函数重载

 

函数重载主要是为了解决两个问题。

  1. 可变参数类型。
  2. 可变参数个数。

另外,一个基本的设计原则是,仅仅当两个函数除了参数类型和参数个数不同以外,其功能是完全相同的,此时才使用函数重载,如果两个函数的功能其实不同,那么不应当使用重载,而应当使用一个名字不同的函数。

好吧,那么对于情况 1 ,函数功能相同,但是参数类型不同,python 如何处理?答案是根本不需要处理,因为 python 可以接受任何类型的参数,如果函数的功能相同,那么不同的参数类型在 python 中很可能是相同的代码,没有必要做成两个不同函数。

那么对于情况 2 ,函数功能相同,但参数个数不同,python 如何处理?大家知道,答案就是缺省参数。对那些缺少的参数设定为缺省参数即可解决问题。因为你假设函数功能相同,那么那些缺少的参数终归是需要用的。

好了,鉴于情况 1 跟 情况 2 都有了解决方案,python 自然就不需要函数重载了。

I'm learning Python (3.x) from a Java background.

I have a python program where I create a personObject and add it to a list.

p = Person("John")
list.addPerson(p)

But for flexibility I also want to be able to declare it directly in the addPerson method, like so:

list.addPerson("John")

The addPerson method will be able to differentiate whether or not I'm sending a Person-object or a String.

In Java I would create two separate methods, like this:

void addPerson(Person p) {
    //Add person to list
}

void addPerson(String personName) {
    //Create Person object
    //Add person to list
}

I'm not able to find out how to do this in Python. I know of a type() function, which I could use to check whether or not the parameter is a String or an Object. However, that seems messy to me. Is there another way of doing it?

EDIT:

I guess the alternative workaround would be something like this(python):

def addPerson(self, person):
    //check if person is string
        //Create person object

    //Check that person is a Person instance
        //Do nothing

    //Add person to list

But it seems messy compared to the overloading solution in Java.

解决方案

Using the reference pointed by @Kevin you can do something like:

from multimethod import multimethod

class Person(object):
    def __init__(self, myname):
        self.name = myname

    def __str__(self):
        return self.name

    def __repr__(self):
        return self.__str__()

@multimethod(list, object)
def addPerson(l, p):
    l = l +[p]
    return l

@multimethod(list, str)
def addPerson(l, name):
    p = Person(name)
    l = l +[p]
    return l

alist = []
alist = addPerson(alist, Person("foo"))
alist = addPerson(alist, "bar")
print(alist)

The result will be:

$ python test.py
[foo, bar]

(you need to install multimethod first)

http://www.it1352.com/779685.html

python pyMysql 自定义异常 函数重载的更多相关文章

  1. 【ZH奶酪】为什么Python不需要函数重载?

    函数重载的作用是什么? 函数重载主要是为了解决两个问题 可变参数类型 可变参数个数 另外,一个基本的设计原则是,仅仅当两个函数除了参数类型和参数个数不同以外,其功能是完全相同的,此时才使用函数重载,如 ...

  2. Python不支持函数重载

    函数重载与Python: 函数重载的好处就是不用为了不同的参数类型或参数个数,而写多个函数.多个函数用同一个名字,但参数表,即参数的个数和数据类型可以不同.调用的时候,虽然方法名字相同,但根据参数表可 ...

  3. python 不需要函数重载

    函数重载主要是为了解决两个问题. 可变参数类型. 可变参数个数. 另外,一个基本的设计原则是,仅仅当两个函数除了参数类型和参数个数不同以外,其功能是完全相同的,此时才使用函数重载,如果两个函数的功能其 ...

  4. Python(十三)python的函数重载

    首先,重载函数的功能是实现参数不同情况下功能相同的函数. 函数重载的目的是解决功能相同的函数的以下问题: 1.参数的类型: 2.参数的个数: 对于情况1,函数功能呢相同,参数不同的情况. python ...

  5. 为什么 Python 没有函数重载?如何用装饰器实现函数重载?

    英文:https://arpitbhayani.me/blogs/function-overloading 作者:arprit 译者:豌豆花下猫("Python猫"公众号作者) 声 ...

  6. python中函数重载和重写

    python 中的重载  在python中,具有重载的思想却没有重载的概念.所以有的人说python这么语言并不支持函数重载,有的人说python具有重载功能.实际上python编程中具有重载的目的缺 ...

  7. python中类的设计问题(一些高级问题探讨,函数重载,伪私有,工厂模式,类方法等)

    从这里再次体现了python语言强大的灵活性.某些在高级语言中看似不严谨需要尽量避免的地方在python中都是允许的. 比如: (1),异常可以用来处理错误 (2),方法,类也都可以视为对象. (3) ...

  8. python中不需要函数重载的原因

    函数重载主要是为了解决两个问题: 1.可变参数类型 2.可变参数个数 并且函数重载一个基本的设计原则是,仅仅当两个函数除了参数类型和参数个数不同以外,其功能是完全相同的,此时才使用函数重载,如果两个函 ...

  9. Python中的操作符重载

    运算符重载是指在方法中拦截内置的操作----当类的实例出现在内置操作中,Python会自动调用自定义的办法,并且返回自定义方法的操作结果.     类可以重载python的操作符 操作符重载使我们的对 ...

随机推荐

  1. JSP报错Syntax error, insert ";" to complete Statement

    org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurred at line: 7 in ...

  2. python java scala 单例模式

    Python class Single2(object): """ 同一个对象 """ __instance = None def __ne ...

  3. Structs复习 命名空间

    引入jar包 web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...

  4. Uni2D 入门 -- Skeletal Animation

    转载 csdn http://blog.csdn.net/kakashi8841/article/details/17615195 Skeletal Animation Uni2D V2.0 引进了一 ...

  5. swift中UIImageView的创建

    let imageView = UIImageView() let imageView1 = UIImageView(frame: CGRectMake(, , , )) // 创建出来的UIImag ...

  6. swift和OC中frame的小差异

    //1.0 OC中 CGRect .CGPoint.CGSize 的结构如下: struct CGRect { CGPoint origin; CGSize size; }; struct CGPoi ...

  7. EF 控制code-first生成的数据库表名的单复数

    原地址:https://blog.csdn.net/winnyrain/article/details/51248410 在Code-First中,默认生成的数据库表的名称为类型的复数形式,如Mode ...

  8. Hadoop集群(一) Zookeeper搭建

    作为Hadoop初学者,自然要从安装入手.而hadoop的优势就是分布式,所以,也一定要安装分布式的系统. 整体安装步骤,包括Zookeeper+HDFS+Hbase,为了文章简洁,我会分三篇blog ...

  9. SpringBoot @Async注解失效分析

    有时候在使用的过程中@Async注解会失效(原因和@Transactional注解有时候会失效的原因一样). 下面定义一个Service: 两个异步执行的方法test03()和test02()用来模拟 ...

  10. spring boot 2 内嵌Tomcat Stopping service [Tomcat]

    我在使用springboot时,当代码有问题时,发现控制台打印下面信息: Connected to the target VM, address: '127.0.0.1:42091', transpo ...