强化Python类或过度工程化

2024-04-16 22:05:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不太熟悉,但已经渐渐喜欢上了。我正在启动我们的第一个Python项目,并正在做一些原型。Python和“Python”中的“异常”概念混淆了我。有人能照一下这个节选吗?我是过度工程化还是缺少一些基本的Python方法?在

class URIPartError(Exception):
pass

class WCFClient(object):
def __init__(self, host, scheme='http', port=80, path='/', user=None, password=None):
    super(WCFClient, self).__init__()

    #Store our variables
    try:
        self.__host = str(host).lower()
        self.__scheme = str(scheme).lower()
        self.__port = int(port)
        self.__path = str(path)
        self.__user = str(user) if user else None
        self.__password = str(password) if password else None
    except (TypeError, ValueError), e:
        raise URIPartError('Invalid URI part')

    #Are our inputs valid?
    if not self.__scheme == 'http' and not self.__scheme == 'https':
        raise URIPartError('Invalid URI scheme')
    if not path.startswith('/') or not path.endswith('/'):
        raise URIPartError('Invalid URI path')

    #Generate valid URI for baseurl
    if (self.__scheme == 'http' and self.__port == 80) or (self.__scheme == 'https' and self.__port == 443):    
        self.__baseurl = '{0}://{1}{2}'.format(self.__scheme, self.__host, self.__path)
    else:
        self.__baseurl = '{0}://{1}:{2}{3}'.format(self.__scheme, self.__host, self.__port, self.__path)

def baseurl(self):
    return self.__baseurl

谢谢!在


Tags: pathselfnonehttphostifportnot
2条回答

考虑到您的WCFClient是如何从object继承的(顺便说一句,只有在使用python2.x时才有意义,因为在python3中这是默认的),调用object类的构造函数是没有意义的。这意味着您可以删除该行

super(WCFClient, self).__init__()

其余的都没问题:)

这里打字没什么问题。你不是坚持类型,而是通过检查值来做正确的事情——如果用户传递了无效的参数,那么引发异常是完全有效的。在

我在这里要说的唯一一点是,在getter中使用“private”双下划线变量是非常不雅观的。与其设置self.__baseurl然后提供baseurl()方法,不如直接设置self.baseurl。在

相关问题 更多 >