... is可用于字符串中相等的关键字.
>>> s = 'str'
>>> s is 'str'
True
>>> s is 'st'
False
Run Code Online (Sandbox Code Playgroud)
我试过了两个__is__(),__eq__()但他们没有工作.
>>> class MyString:
... def __init__(self):
... self.s = 'string'
... def __is__(self, s):
... return self.s == s
...
>>>
>>>
>>> m = MyString()
>>> m is 'ss'
False
>>> m is 'string' # <--- Expected to work
False
>>>
>>> class MyString:
... def __init__(self):
... self.s = 'string'
... def __eq__(self, s):
... return …Run Code Online (Sandbox Code Playgroud) 给定方法的引用,有没有办法检查方法是否绑定到对象?你还可以访问它绑定的实例吗?
我正在使用Python 2.x,我有一个我正在从以太召唤的对象; 关于它的文件不是特别清楚.我希望能够获得该对象的属性列表以及每个属性的类型.
同样,我想获得该对象的方法列表,以及我可以在该方法上找到的任何其他信息,例如参数的数量和它们各自的类型.
我有一种感觉,我只是在Google搜索中错过了正确的术语.并不是说我想破坏具体细节,但它是Active Directory,所以这总是很有趣.
当我说"python属性查找进程"时,我的意思是:当你编写x.foo时python会做什么?
搜索网络我没有找到很多关于这个的文档,我发现的最好的论文之一恢复了以下步骤的过程(你可以在这里看到完整的文章)
起初这可能看似正确,但属性查找过程稍微复杂一些,例如对于x.foo,如果x是类或实例,它的行为不一样.
我找到了一些无法通过这种方式解释的样本.考虑以下python代码:
class Meta(type):
def __getattribute__(self, name):
print("Metaclass getattribute invoked:", self)
return type.__getattribute__(self, name)
def __getattr__(self, item):
print('Metaclass getattr invoked: ', item)
return None
class C(object, metaclass=Meta):
def __getattribute__(self, name):
print("Class getattribute invoked:", args)
return object.__getattribute__(self, name)
c=C()
Run Code Online (Sandbox Code Playgroud)
现在使用相应的输出检查以下行:
>> C.__new__
Metaclass getattribute invoked: <class '__main__.C'>
<built-in method __new__ of type object at 0x1E1B80B0>
>> C.__getattribute__
Metaclass …Run Code Online (Sandbox Code Playgroud) 这里有一个惊喜:
>>> class B:
... print(locals())
... def foo(self):
... print(locals())
... print(__class__ in locals().values())
...
{'__module__': '__main__', '__qualname__': 'B'}
>>> B().foo()
{'__class__': <class '__main__.B'>, 'self': <__main__.B object at 0x7fffe916b4a8>}
True
Run Code Online (Sandbox Code Playgroud)
似乎只是提到__class__了解析器明确检查了吗?否则我们应该得到类似的东西
NameError: name '__class__' is not defined
Run Code Online (Sandbox Code Playgroud)
实际上,如果您修改为仅检查密钥,即检查'__class__' in locals(),那么我们只self在预期范围内.
如何将这个变量神奇地注入范围?我的猜测是与此有关super- 但我没有使用super,那么为什么编译器在不需要时会在这里创建一个隐式闭包引用呢?
我希望能够做到:
>>> class a(str):
... pass
...
>>> b = a()
>>> b.__class__ = str
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: only for heap types
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个对象代理。属性/属性查找可以通过简单地实现__getattribute__,__setattr__和__delattr__方法来完成。但是,其他功能如len(x), x[], bool(x)需要其他 dunder 方法__len__, __getitem__, __bool__来实现。如果您没有在代理类上实现这些,但是您代理的对象支持它们,您的代理将不完整并导致运行时错误。
因此,我想拥有一份我需要实施的所有事情的综合清单,但我在网上找不到任何可靠的清单。
这是我从typing和builtins模块中获得的 97 个独特的 dunder 方法名称。我知道他们中的很多人在做什么,但有些人我不知道。为我的代理类实现所有或大部分它们会很痛苦,所以如果有解决方法我会很高兴。
__abs__
__add__
__aenter__
__aexit__
__aiter__
__and__
__anext__
__await__
__bool__
__bytes__
__call__
__class__
__cmp__
__complex__
__contains__
__delattr__
__delete__
__delitem__
__delslice__
__dir__
__div__
__divmod__
__enter__
__eq__
__exit__
__float__
__floordiv__
__format__
__fspath__
__ge__
__get__
__getattribute__
__getitem__
__getnewargs__
__getslice__
__gt__
__hash__
__iadd__
__iand__
__import__
__imul__
__index__
__init__
__init_subclass__
__instancecheck__
__int__
__invert__
__ior__
__isub__
__iter__
__ixor__
__le__
__len__ …Run Code Online (Sandbox Code Playgroud) 在Java中我可以通过使用a Iterator然后使用.remove()迭代器的方法来删除迭代器返回的最后一个元素,如下所示:
import java.util.*;
public class ConcurrentMod {
public static void main(String[] args) {
List<String> colors = new ArrayList<String>(Arrays.asList("red", "green", "blue", "purple"));
for (Iterator<String> it = colors.iterator(); it.hasNext(); ) {
String color = it.next();
System.out.println(color);
if (color.equals("green"))
it.remove();
}
System.out.println("At the end, colors = " + colors);
}
}
/* Outputs:
red
green
blue
purple
At the end, colors = [red, blue, purple]
*/
Run Code Online (Sandbox Code Playgroud)
我将如何在Python中执行此操作?我在for循环中迭代它时无法修改列表,因为它会导致跳过东西(参见此处).并且似乎没有相当于IteratorJava 的接口.
根据object.__eq__()文档,默认(即在object类中)实现==如下:
True if x is y else NotImplemented
Run Code Online (Sandbox Code Playgroud)
仍然遵循的文档NotImplemented,我推断这NotImplemented意味着 Python 运行时将尝试以相反的方式进行比较。y.__eq__(x)即如果x.__eq__(y)返回则尝试NotImplemented(在运算符的情况下==)。
现在,在 python 3.9 中False打印以下代码:True
class A:
pass
print(A() == A())
print(bool(NotImplemented))
Run Code Online (Sandbox Code Playgroud)
所以我的问题如下:文档在哪里提到了NotImplemented在上下文中的特殊行为__eq__?
PS:我在CPython 源代码中找到了答案,但我想这必须/应该在文档中的某个位置。
python-datamodel ×10
python ×9
python-3.x ×2
attributes ×1
built-in ×1
closures ×1
iterator ×1
list ×1
loops ×1
proxy-object ×1