相关疑难解决方法(0)

单个if语句中谓词的正确平衡在哪里?

我个人对以下代码没有任何问题

if (Object foo != null && !String.IsNullOrEmpty(foo["bar"]))
{
    // do something
}
Run Code Online (Sandbox Code Playgroud)

因为我认为以下内容过于冗长

if (Object foo != null)
{
    if (!String.IsNullOrEmpty(foo["bar"]))
    {
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果说有5个谓词并且我不得不将文本包装在编辑器中以便立即查看它们,那么我不会在这个观点上走得那么远,是否有一条逻辑"线"可以描绘出你有多少谓词在类似意义上包含在单个if语句中,表示方法永远不需要超过7个参数

language-agnostic coding-style

8
推荐指数
3
解决办法
463
查看次数

dir()中hasattr()和'attribute'之间有什么区别?

例如:

>>> s = 'string'
>>> hasattr(s, 'join')
True
>>> 'join' in dir(s)
True
Run Code Online (Sandbox Code Playgroud)

Python文档说,hasattr实现调用getattr并查看它是否引发异常.然而,这导致了很大的开销,因为丢弃了所获得的值并且可能引发异常.

问题是,如果呼叫'attribute' in dir(obj)意味着同一件事,它是否更快,更安全,还是在特定场合可能失败?

python

5
推荐指数
2
解决办法
2328
查看次数

python 是否有速记来检查对象是否具有属性?

背景是我从 JSON API 获取数据,其中许多字段是可选的,我想要数据库中的大部分字段。当特定字段不可用时,我希望将空字符串 ( "") 写入数据库。

目前我一直在做:

if jsonobject.what_i_look_for:
  dbstring = jsonobject.what_i_look_for
else:
  dbstring = ""
Run Code Online (Sandbox Code Playgroud)

然后将dbstring插入到数据库中。然而,我现在得到了更多这些字段,我想要一个更清晰的代码,而不是一个包含大约 80% 的 if 语句的函数。

我找到了if-shorthandsthis shorthand 来检查变量是否为空,但两者似乎都不能直接作为字符串工作。我已经print()在交互式 python 3.5.2 shell 中对此进行了测试:

>>> print(testvar or "")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'testvar' is not defined

>>> print(testvar if testvar else "")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'testvar' is not defined
Run Code Online (Sandbox Code Playgroud)

这: …

python string if-statement conditional-operator python-3.x

5
推荐指数
1
解决办法
7916
查看次数

检查python中是否有任何属性的任何替代方法?

a = SomeClass()
if hasattr(a, 'property'):
        a.property
Run Code Online (Sandbox Code Playgroud)

这是检查是否有房产的唯一方法吗?有没有其他方法可以做同样的事情?

python attributes

3
推荐指数
2
解决办法
1084
查看次数

Python Django检查属性是否存在或是否已设置

我有一个User对象和一个UserInfo具有一对一关系的对象.我只是添加UserInfo对象,所以一些用户已经有User对象,但没有UserInfo对象.我想检查User对象是否有与之关联的UserInfo对象,如果没有将它们重定向到我可以获取一些信息的页面.我仍然是python的新手,并尝试做一个if request.user.user_info:在它不存在时抛出异常所以我最终这样做:

 user = request.user
    try:
        user.user_info.university
    except:
        print 'redirect to info page'
Run Code Online (Sandbox Code Playgroud)

哪个工作正常,但我觉得异常应该是异常,而不是if语句替换.有一个更好的方法吗?

python django

3
推荐指数
1
解决办法
7312
查看次数

是否有任何对象可以使str()函数在python中抛出错误或异常?

我有一个函数,要求输入是一个字符串.

我知道我可以断言或检查输入类型,但我想尽可能地处理它.

我有以下代码来处理它.但我想知道是否有任何情况,这一行可以抛出我需要处理的异常.

def foo(any_input):
    clean_input = str(any_input) # will this throw any exception or error?
    process(clean_input)
Run Code Online (Sandbox Code Playgroud)

python string exception

3
推荐指数
3
解决办法
1110
查看次数

测试Python类中的特定方法

测试一个类是否定义了特定方法的最佳(或'Pythonic')方法是什么?

这两种方法都有效,但感觉不正确,因为在第二种方法中,我只是尝试访问它并捕获异常(如果它不存在).

有更好/更正确的方法吗?

class TestClass(object):
    def TestFunc(self):
        pass



if 'TestFunc' in dir(TestClass):
    print 'yes'
else:
    print 'No'



try:
    if TestClass.__getattribute__(TestClass, 'TestFunc'):
        print 'yes'

except:
    print 'No'
Run Code Online (Sandbox Code Playgroud)

python oop methods class

2
推荐指数
1
解决办法
179
查看次数

如何忽略Python对象中未定义的属性?

我有一个Python字典,用于标记属性的键名.与此字典关联的程序设置为仅包含一些项目,并且仅在必要时才设置.因此,并非字典中的所有属性都在此脚本的每次传递中定义.

这是带字典的代码

def getWidths(self,sheetName):
    sheets = {
        'dclabels':self.dclabels,
        'tdclabels':self.tdclabels
    }

    sheetName = sheetName.lower()
    if sheetName in sheets: 
        return sheets.get(sheetName) 
    else:
        return self.colWidths
Run Code Online (Sandbox Code Playgroud)

我收到错误说明AttributError: ClassName instance has no attribute 'dclabels' 如何避免此错误?有没有办法让脚本忽略任何未定义的属性?谢谢!

我找到了解决问题的方法.

   def getWidths(self,sheetName):
       if hasattr(self, sheetName.lower()):
           name = getattr(self,sheetName.lower())
           self.name = name
           return self.name
       else:
           return self.colWidths
Run Code Online (Sandbox Code Playgroud)

我利用了hasattr()getattr()解决了我的问题.感谢大家的建议.

python dictionary

2
推荐指数
1
解决办法
2253
查看次数

Python如何打印itertools.permutations的属性

我是Python新手,我正在尝试itertools:

import itertools as it
obj = it.permutations(range(4))
print(obj)
for perm in obj:
    print( perm )
Run Code Online (Sandbox Code Playgroud)

我的问题:如何在不使用循环的情况下obj 直接查看/打印所有排列for

我尝试了什么: 我尝试使用__dict__vars在这个SO链接中建议,但两个都不起作用(前者似乎不存在对象,而后者生成'TypeError:'itertools.permutations'对象不可调用').

请原谅,如果我的问题相当无趣 - 这个属性问题看起来很复杂,大部分用SO链接写的东西飞过我的头脑.

python attributes python-itertools

1
推荐指数
1
解决办法
234
查看次数