如果我有一个对象列表,我可以使用该__cmp__方法来覆盖对象进行比较.这会影响==操作员的工作方式和item in list功能.但是,它似乎没有影响item in set函数 - 我想知道如何更改MyClass对象,以便我可以覆盖集合比较项目的行为.
例如,我想创建一个在底部的三个print语句中返回True的对象.目前,最后一个print语句返回False.
class MyClass(object):
def __init__(self, s):
self.s = s
def __cmp__(self, other):
return cmp(self.s, other.s)
instance1, instance2 = MyClass("a"), MyClass("a")
print instance2==instance1 # True
print instance2 in [instance1] # True
print instance2 in set([instance1]) # False
Run Code Online (Sandbox Code Playgroud) 如果我有一个字符串参数的python函数需要在一个特定的值列表中,那么处理这个问题的最佳方法是什么?是否存在在文档字符串或任何内容中表达此内容的约定?
例如.
def makeShape(shape):
assert shape in ["circle", "square", "triangle"]
Run Code Online (Sandbox Code Playgroud)
有没有更好的方式来表达形状应该始终是这三个值之一?
这是我一直试图做的事情,而且更像是一个开放式的问题.如果任何人有任何知识可以帮助我阐明这一点,我将非常感激.
我想在mp3中解码音频流并使用它来驱动动画,所有这些都使用python.根据我的理解,mp3中的音频数据存储在32个频率子带(或频率区间)的帧中,这对我来说是理想的 - 如果我可以拍摄mp3并为每个帧上的每个子带提取幅度,那么非常适合我想做的事情.
我在这里找到了解决方案https://bitbucket.org/portalfire/pymp3,其中所有处理似乎都是在python中完成的.它很慢,但即使我可以使用它来提取我想要的东西,它也会很好 - 我很难理解该代码中发生了什么.我也有一个解决方案,我转换为wav然后使用fft从wav中提取频率.这是非常嘈杂的,似乎是一种愚蠢的方式,因为我想要的数据直接存储在mp3中 - 转换回声波似乎是不必要的.这实际上比第一个更快.这是我最终得到的:
http://www.youtube.com/watch?v=f_0FORxlK4A
好吧,如果有人有任何建议或想要分享的经验,或者我应该看看图书馆的想法,我真的很想听.
谢谢!
亨利
我想使用new.instancemethod将函数(aFunction)从一个类(A)分配给另一个类(B)的实例.我不知道如何让aFunction允许自己应用于B的实例 - 目前我收到一个错误,因为aFunction期望在A的实例上执行.
[注意:我无法使用__class__属性将实例强制转换为A,因为我正在使用的类(在我的示例中为B)不支持类型转换]
import new
class A(object):
def aFunction(self):
pass
#Class which doesn't support typecasting
class B(object):
pass
b = B()
b.aFunction = new.instancemethod(A.aFunction, b, B.__class__)
b.aFunction()
Run Code Online (Sandbox Code Playgroud)
这是错误:
TypeError: unbound method aFunction() must be called with A instance as first argument (got B instance instead)
Run Code Online (Sandbox Code Playgroud) 我在maya中使用了PyQt4,通常我发现切换到PySide很容易,但是我无法获得指向主窗口的指针.也许有人可以理解出了什么问题.
这是我在PyQt4中所做的:
import sip, PyQt4.QtCore
import maya.OpenMayaUI as mui
ptr = mui.MQtUtil.mainWindow()
parent = sip.wrapinstance(long(ptr), PyQt4.QtCore.QObject)
Run Code Online (Sandbox Code Playgroud)
这很好用.当我在PySide中尝试相同时:
import sip, PySide.QtCore
import maya.OpenMayaUI as mui
ptr = mui.MQtUtil.mainWindow()
parent = sip.wrapinstance(long(ptr), PySide.QtCore.QObject)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
# Error: wrapinstance() argument 2 must be sip.wrappertype, not Shiboken.ObjectType
# Traceback (most recent call last):
# File "<maya console>", line 4, in <module>
# TypeError: wrapinstance() argument 2 must be sip.wrappertype, not Shiboken.ObjectType #
Run Code Online (Sandbox Code Playgroud)
谁知道出了什么问题?
我需要覆盖类中的插入符行为,但我不确定哪个操作符重载适用于它.例如:
class A:
def __init__(self, f):
self.f = f
def __caret__(self, other):
return self.f^other.f
print A(1)^A(2)
Run Code Online (Sandbox Code Playgroud)
此代码错误:
TypeError: unsupported operand type(s) for ^: 'instance' and 'instance'
Run Code Online (Sandbox Code Playgroud)
我如何构建类以便控制行为?