有没有办法在Python中确定对象是否具有某些属性?例如:
>>> a = SomeClass()
>>> a.someProperty = value
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
Run Code Online (Sandbox Code Playgroud)
在使用之前如何判断是否a具有该属性property?
我一直在阅读一些源代码,在一些地方我已经看到了它的用法assert.
这究竟是什么意思?它的用途是什么?
我发现Python的断言语句是捕获永远不会发生的情况的好方法.当代码被认为是正确的时,可以通过Python优化删除它.
它似乎是在调试模式下运行Python应用程序的完美机制.但是看看django,twisted和zope等几个Python项目,assert几乎从未使用过.那么,为什么会这样呢?
为什么在Python社区中不经常使用断言语句?
我正在寻找一种有效的方法来检查python函数的变量.例如,我想检查参数类型和值.有这个模块吗?或者我应该使用类似装饰器或任何特定习语的东西?
def my_function(a, b, c):
"""an example function I'd like to check the arguments of."""
# check that a is an int
# check that 0 < b < 10
# check that c is not an empty string
Run Code Online (Sandbox Code Playgroud) 如何格式化符合PEP8的长断言语句?请忽略我的例子的人为性质.
def afunc(some_param_name):
assert isinstance(some_param_name, SomeClassName), 'some_param_name must be an instance of SomeClassName, silly goose!'
Run Code Online (Sandbox Code Playgroud)
无法将其包装在括号中,因为它会更改assert语句的行为,因为它是关键字,而不是内置函数.
在函数中,我想确保参数a和b具有相同的长度.如果不遵守,我想为此提出异常.我知道ValueError用于异常,其中参数本身不符合某些特定条件.在这种情况下,如果条件在参数之间,那么ValueError是一个适当的错误吗?如果没有,任何标准的Python异常更合适吗?
def func(a, b):
if len(a) != len(b):
raise ValueError("list a and list b must have the same length")
Run Code Online (Sandbox Code Playgroud) 我有一类叫做Node一个具有importancesetter和getter,如下:
class Node:
@property
def importance(self):
return self._importance
@importance.setter
def importance(self, new_importance):
if new_importance is not None:
new_importance = check_type_and_clean(new_importance, int)
assert new_importance >= 1 and new_importance <= 10
self._importance = new_importance
Run Code Online (Sandbox Code Playgroud)
后来,我有一个Theorem继承自的类Node.就所涉及的而言,a Theorem和a 之间的唯一区别是必须具有至少一个.NodeimportanceTheoremimportance3
一个定理如何能继承的importance二传手,但增加的附加约束importance >= 3?
我试着这样做:
class Theorem(Node):
@importance.setter
def importance(self, new_importance):
self.importance = new_importance # hoping this would use the super() setter
assert self.importance >= 3
Run Code Online (Sandbox Code Playgroud) 是否存在一个小的,独立的库,它会将基于文本格式(例如LaTeX或MathML)的方程式渲染为图像(矢量或栅格)?
如果它是Python或Python友好的话会更好.
(我发现的一种可能性:Matplotlib使用 Python代码来解析和显示LaTeX方程,使用gl2ps.如果我没有找到任何其他内容,似乎可以将所有相关位提取到一个单独的库中.)
编辑:通过"自包含"我的意思是他们不能使用TeX/LaTex本身,因为不幸的是我不能依赖它被安装
我有一个namedtuple 变量,它代表应用程序的版本(它的编号和类型)。但我想对值进行一些限制:
Version = namedtuple("Version", ["app_type", "number"])
version = Version("desktop") # i want only "desktop" and "web" are valid app types
version = Version("deskpop") # i want to protect from such mistakes
Run Code Online (Sandbox Code Playgroud)
我现在的解决方案是没有方法的原始类:
class Version:
def __init__(self, app_type, number):
assert app_type in ('desktop', 'web')
self.app_type = app_type
self.number = number
Run Code Online (Sandbox Code Playgroud)
它是pythonic吗?是否矫枉过正?
类不变量肯定在编码中很有用,因为它们可以在检测到清晰编程错误时提供即时反馈,并且还可以提高代码可读性,因为它们可以明确说明哪些参数和返回值.我确信这也适用于Python.
但是,通常在Python中,对参数的测试似乎不是"pythonic"做事的方式,因为它违背了鸭子的成语习惯.
我的问题是:
什么是Pythonic在代码中使用断言的方法?
例如,如果我有以下功能:
def do_something(name, path, client):
assert isinstance(name, str)
assert path.endswith('/')
assert hasattr(client, "connect")
Run Code Online (Sandbox Code Playgroud)更一般地说,当断言太多时?
我很高兴听到你对此的看法!
python ×10
assert ×3
oop ×2
python-3.x ×2
arguments ×1
assertions ×1
attributes ×1
debugging ×1
equation ×1
exception ×1
function ×1
inheritance ×1
invariants ×1
latex ×1
mathml ×1
namedtuple ×1
parsing ×1
pep8 ×1