小编tk-*_*dle的帖子

无法在类方法内访问 Dundered 全局变量

我正在经历一个模糊的(对我来说)范围界定的模糊效果,并试图找出它的规则:

#!/usr/bin/env python3

stuff = "the things"
__MORE_STUFF = "even more"

class Thing:
    def __init__(self):
        global __MORE_STUFF # doesn't help
        print(stuff) # is OK
        print(__MORE_STUFF) # fail!

Thing()
Run Code Online (Sandbox Code Playgroud)

结果是

$ python3 dunder.py
the things
Traceback (most recent call last):
  File "dunder.py", line 12, in <module>
    Thing()
  File "dunder.py", line 10, in __init__
    print(__MORE_STUFF) # fail!
NameError: name '_Thing__MORE_STUFF' is not defined
Run Code Online (Sandbox Code Playgroud)

应该是模块全局变量的内容被视为类级属性 - 由于未定义,因此被标记为未定义。

我一直在尝试查看相关文档,但我似乎无法弄清楚规则是什么。

谁能指出我合适的文档吗?

python global

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

When can string slice `&amp;str` produced by a function be returned in Rust?

I've managed to cook up three scenarios which to me seem on the surface to be the same, but behave differently, and I would appreciate if someone could clarify to me why...

The first scenario fails to complile, as I would actually expect :

fn main() {
    let data = get_data();
    println!("{}", data);
}

fn get_data() -> &'static str {
    let x: String = String::from("hello");
    return x.as_str(); // always fails with ownership issue
}
Run Code Online (Sandbox Code Playgroud)

Fails as expected: returns a reference …

rust

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

标签 统计

global ×1

python ×1

rust ×1