gpt4 book ai didi

用户定义函数中的python前导和尾随下划线

转载 作者:太空宇宙 更新时间:2023-11-04 10:08:30 25 4
gpt4 key购买 nike

我如何使用 rt 函数,据我所知,前导和尾随下划线 __and__() 可用于 native python 对象,或者您不想在特定情况下自定义行为。用户如何利用它。例如:在下面的代码中我可以使用这个函数吗,

class A(object):
def __rt__(self,r):
return "Yes special functions"


a=A()
print dir(a)
print a.rt('1') # AttributeError: 'A' object has no attribute 'rt'

但是

class Room(object):



def __init__(self):
self.people = []

def add(self, person):
self.people.append(person)

def __len__(self):
return len(self.people)



room = Room()
room.add("Igor")
print len(room) #prints 1

最佳答案

Python 不会将一个名称翻译成另一个名称。如果已定义,特定操作将在幕后调用__special_method__。例如,Python 调用 __and__ 方法来 Hook & 运算符,因为 Python 解释器显式查找该方法 并记录如何应该使用它。

换句话说,调用 object.rt() 不会在任何地方自动转换为 object.__rt__()

请注意,Python 保留 这样的名称; future 版本的 Python 可能会将该名称用于特定目的,然后您现有的代码使用 __special_method__ 名称用于您自己的目的将会中断。

来自Reserved classes of identifiers section :

__*__
System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

您当然可以忽略该建议。在这种情况下,您必须编写实际调用您的方法的代码:

class SomeBaseClass:
def rt(self):
"""Call the __rt__ special method"""
try:
return self.__rt__()
except AttributeError:
raise TypeError("The object doesn't support this operation")

SomeBaseClass 的子类。

同样,Python 不会自动调用您的新方法。您仍然需要实际编写这样的代码。

关于用户定义函数中的python前导和尾随下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39637164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com