小编Too*_*one的帖子

我们如何获得__repr __()的默认行为?

如果有人在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>

python repr representation python-3.x

15
推荐指数
3
解决办法
1866
查看次数

`__del__` 和 `__delete__` 有什么区别?

__del__假设有人不知道和之间有什么区别__delete__?写一个解释。

python destructor destruction python-3.x

6
推荐指数
1
解决办法
7534
查看次数

我们如何在不使用“def”关键字的情况下定义函数?

可以不使用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)

我们如何为函数做类似的事情?也就是说,我们如何在不使用deforlambda关键字的情况下定义函数?dehf如果以下两段代码创建相同的s ,纯 python 实现会是什么样子foo

def foo(bar):
    bar += 934
    return bar

foo = dehf(blah, blah, blah, blah, [...])
Run Code Online (Sandbox Code Playgroud)

python function python-3.x

5
推荐指数
1
解决办法
6052
查看次数

我们如何检查函数是否在Python中返回多个值?

这个问题已经被问到,但我想问一些巧妙的不同.

我们如何确定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 return-type return-value python-3.x

4
推荐指数
1
解决办法
77
查看次数

我们如何强制为魔术方法(特殊方法)调用 getattribute() ?

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 …

python metaclass class new-style-class python-3.x

4
推荐指数
2
解决办法
384
查看次数

为什么我不能继承 Enum 的子类?

考虑以下代码:

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_

python enums python-3.x

4
推荐指数
1
解决办法
7093
查看次数

在Python列表中/内部拆分

我有一个包含以下内容的列表:

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)

python

4
推荐指数
1
解决办法
97
查看次数

当我无法处理异常时,为什么退出代码为零(“良好”)?

考虑以下代码片段以及从控制台获得的打印输出:

片段1

表现还好。一切都是卑鄙的。

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)

片段2

也表现得很好。一切都是卑鄙的。

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)

片段3

我不明白为什么以下情况不会导致未处理的异常打印到控制台:

def e():
    try:
        raise ValueError()
        x = y + z
        L = [1, 2, …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

3
推荐指数
1
解决办法
64
查看次数

使用“threading”模块时出现问题 - AttributeError:模块“threading”没有属性“RLock”

我收到以下错误:

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)

python multithreading python-3.x

3
推荐指数
1
解决办法
3299
查看次数

如何覆盖 python 的“not in”运算符

我意识到那__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 operator-overloading python-3.x

2
推荐指数
1
解决办法
671
查看次数