如果有人在python中编写一个类,并且未能指定自己的__repr__()
方法,则为它们提供默认方法.但是,假设我们要编写一个与默认行为具有相同或相似行为的函数__repr__()
.但是,我们希望此函数具有默认__repr__()
方法的行为,即使__repr__()
该类的实际重载也是如此.也就是说,假设我们想要编写一个与默认行为具有相同行为的函数,__repr__()
而不管是否有人重载了该__repr__()
方法.我们怎么做?
class DemoClass:
def __init__(self):
self.var = 4
def __repr__(self):
return str(self.var)
def true_repr(x):
# [magic happens here]
s = "I'm not implemented yet"
return s
obj = DemoClass()
print(obj.__repr__())
print(true_repr(obj))
Run Code Online (Sandbox Code Playgroud)
print(obj.__repr__())
打印4
,但print(true_repr(obj))
打印如下:
<__main__.DemoClass object at 0x0000000009F26588>
__del__
假设有人不知道和之间有什么区别__delete__
?写一个解释。
可以不使用class
关键字来定义类。
下列 ...
get_i = lambda self: self.i
get_i.__name__ = 'get_i'
get_i.__qualname__ = 'Klass2.get_i'
dct = dict(a=1, i=4, get_i=get_i)
Klass2 = type('Klass2', (SuperK,), dct)
Run Code Online (Sandbox Code Playgroud)
...产生与以下相同的最终结果:
class Klass1(SuperK):
a = 1
i = 4
def get_i(self):
return self.i
Run Code Online (Sandbox Code Playgroud)
我们如何为函数做类似的事情?也就是说,我们如何在不使用def
orlambda
关键字的情况下定义函数?dehf
如果以下两段代码创建相同的s ,纯 python 实现会是什么样子foo
?
def foo(bar):
bar += 934
return bar
foo = dehf(blah, blah, blah, blah, [...])
Run Code Online (Sandbox Code Playgroud) 这个问题已经被问到,但我想问一些巧妙的不同.
我们如何确定python函数是否返回多个值,而不调用函数?有没有办法找到更像编译时而不是在运行时的东西?(我意识到python是一种解释语言)
以下是不可能的:
r = demo_function(data) # takes more than 5 minutes to run
if (not len(r) == 2) or (not isinstance(r, tuple)):
raise ValueError("I was supposed to return EXACTLY two things")
Run Code Online (Sandbox Code Playgroud)
所以是:
try:
i, j = demo_function(data)
# I throw TypeError: 'int' object is not iterable
except ValueError:
raise ValueError("Hey! I was expecting two values.")
except TypeError:
s1 = "Hey! I was expecting two values."
s2 = "Also, TypeError was thrown, not ValueError" …
Run Code Online (Sandbox Code Playgroud) 在Python文档,各国__getattribute__
可以查找特殊的方法时被绕过。这是通过语言语法或内置函数进行隐式调用的结果。
例如,
elem = container[0]
Run Code Online (Sandbox Code Playgroud)
不等同于:
elem = container.__getattribute__('__getitem__')[0]
Run Code Online (Sandbox Code Playgroud)
下面是另一个例子:
class WrappedList:
def __init__(self):
object.__setattr__(self, 'interal_list', ['apple', 'pear', 'orange'])
def __getattribute__(self, attr_name):
interal_list = object.__getattribute__(self, 'interal_list')
attr = getattr(interal_list, attr_name)
return attr
wl = WrappedList()
print("\nSTART TEST 01 ------------------------")
try:
print(wl[0]) # throws TypeError: 'WrappedList' object does not support indexing
except TypeError as e:
print(e)
print("\nSTART TEST 02 ------------------------")
try:
getitem = getattr(wl, '__getitem__')
print(getitem(0)) # works just fine
except TypeError as e:
print(e)
Run Code Online (Sandbox Code Playgroud)
我想编写一个名为的MagicOverrider …
考虑以下代码:
from enum import Enum
class SubclassOfEnum(Enum):
x = 5
print(SubclassOfEnum.x)
class SubSubclassOfEnum(SubclassOfEnum):
y = 6
print(SubSubclassOfEnum.y)
Run Code Online (Sandbox Code Playgroud)
我们得到一个错误TypeError: Cannot extend enumerations
,,
从:Python36\lib\enum.py", line 436, in _get_mixins_
我有一个包含以下内容的列表:
x = ['1', '2/keys', '3']
Run Code Online (Sandbox Code Playgroud)
现在,必须将“ 2 /键”拆分。我认为应该可以在列表中创建一个列表?但是在拆分之前,我必须检查一下是否存在“ /
”。
以下代码,显然是行不通的,是我得到的:
for numbers in x:
if '/' in x:
x[numbers].split('/')
Run Code Online (Sandbox Code Playgroud)
是否有可能产生如下结果:
x = ['1', ['2', 'keys'], '3']
Run Code Online (Sandbox Code Playgroud) 考虑以下代码片段以及从控制台获得的打印输出:
表现还好。一切都是卑鄙的。
try:
raise ValueError()
finally:
print(3)
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
File "D:/FILE_MGMT_PYTHON/fbzdfbhedrh.py", line 5, in <module>
raise ValueError()
ValueError
3
Run Code Online (Sandbox Code Playgroud)
也表现得很好。一切都是卑鄙的。
try:
raise ValueError()
except type("", (Exception,), dict()):
print("this is not supposed to print")
finally:
print(3)
Run Code Online (Sandbox Code Playgroud)
3
Traceback (most recent call last):
File "D:/FILE_MGMT_PYTHON/fbzdfbhedrh.py", line 14, in <module>
raise ValueError()
ValueError
Run Code Online (Sandbox Code Playgroud)
我不明白为什么以下情况不会导致未处理的异常打印到控制台:
def e():
try:
raise ValueError()
x = y + z
L = [1, 2, …
Run Code Online (Sandbox Code Playgroud) 我收到以下错误:
AttributeError: module 'threading' has no attribute 'RLock'
Exception ignored in: <module 'threading' from 'D:\\PYTHON_STACKOVERFLOW_ANSWERS\\threading.py'>
AttributeError: module 'threading' has no attribute '_shutdown'
Run Code Online (Sandbox Code Playgroud)
我的代码如下所示:
import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting", name)
time.sleep(2)
logging.info("Thread %s: finishing", name)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(
format=format,
level=logging.INFO,
datefmt="%H:%M:%S"
)
logging.info("Main : before creating thread")
x = threading.Thread(target=thread_function, args=(1,))
logging.info("Main : before running thread")
x.start()
logging.info("Main : wait for the thread to finish")
# x.join()
logging.info("Main : …
Run Code Online (Sandbox Code Playgroud) 我意识到那__contains__
是“in”运算符。我还意识到,默认情况下“not in”是 的否定__contains__
。然而,很多 python 文档都列出了“not in”,就好像它是与“in”不同的运算符。就像
and 一样__contains__
,其中有两个运算符,一个通常是另一个的否定?如果是这样,正确的双下划线使用是什么?__eq__
__ne__
__<name>__
def __init__(self):
self.numbers = [1,2,3,4,54]
def __contains__(self, key):
return key in self.numbers
Run Code Online (Sandbox Code Playgroud) python ×10
python-3.x ×9
class ×1
destruction ×1
destructor ×1
enums ×1
function ×1
metaclass ×1
repr ×1
return-type ×1
return-value ×1