小编BAK*_* ZQ的帖子

如何在Python函数作用域内获取类型注释?

例如:

def test():
    a: int
    b: str
    print(__annotations__)
test()
Run Code Online (Sandbox Code Playgroud)

该函数调用会引发NameError: name '__annotations__' is not defined错误。

我想要的是获取 function 中的类型注释test,例如全局范围或类范围中注释的返回字典。

有什么方法可以实现这一点吗?

如果不可能,为什么存在这种语法?

python annotations type-hinting python-3.x

8
推荐指数
1
解决办法
4877
查看次数

为什么 const char[] 的类型推导与 const char * 不同?

在第一次调用中,当我将 a 传递给char const []一个参数为 的模板函数时T const aT推断出char const *这是合理的,因为const指的是衰减指针。

但是,当参数类型更改为 时T const & aT推导为char[7]。从上面的角度来看,为什么不const限定整个数组类型?

template <typename T>
void show1(T const a) {
     // input is const char *
     // T is char const *
     // a is char const * const
}

template <typename T>
void show2(T const & a) {
     // input is char const [7]
     // T is char[7] …
Run Code Online (Sandbox Code Playgroud)

c++ arrays templates constants

7
推荐指数
1
解决办法
160
查看次数

如果用var重新声明将对现有变量产生影响

const show1 = function(x, y = () => {x = 2; return x;}) {
    let x = 3;
    console.log(y());
    console.log(x);
};
show1();
Run Code Online (Sandbox Code Playgroud)

const show2 = function(x, y = () => {x = 2; return x;}) {
    x = 3;
    console.log(y());
    console.log(x);
};
show2();
Run Code Online (Sandbox Code Playgroud)

const show3 = function(x, y = () => {x = 2; return x;}) {
    var x = 3;
    console.log(y());
    console.log(x);
};
show3();
Run Code Online (Sandbox Code Playgroud)

输出

show1: Uncaught SyntaxError: Identifier 'x' has already been decalred;
show2: 2 2
show3: 2 …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6

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

超类的 __init__ 未使用数据类调用

我正在通过继承asyncio.Future一些自定义属性来创建一个作业类,并期望作业实例的功能与原始 Future 类似。

当我job.set_result在协程内部调用时,它会引发 a Future object is not initialized error,然后我尝试通过调用初始化 futureasyncio.ensure_future并出现相同的错误。

我尝试了更多,发现未来通常是由 创造的loop.create_future(),但是,没有选项来创建我的自定义未来。

下面是一个示例,如何初始化我的自定义未来?

import asyncio
from dataclasses import dataclass

@dataclass
class Job(asyncio.Future):
    job_task: Callable
    real_future: asyncio.Future = None
    something: str = None

    def schedule(self):
        async def run():
            res = await self.job_task()
            self.set_result(res) # raise error, future not initialized
            return res
        self.real_future = asyncio.ensure_future(run())

async def main():
    async def task():
        await asyncio.sleep(1)
        return 1
    job = Job(task)
    job.schedule()
    await job …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-dataclasses

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