相关疑难解决方法(0)

在 __init__ 中更改时,python 类变量可以成为实例变量吗?

据我了解,这里var是一个类变量:

class MyClass:
    var = 'hello'

    def __init__(self):
        print(self.var)
Run Code Online (Sandbox Code Playgroud)

那是一个实例变量:

class MyClass:

    def __init__(self, var):
        self.var = var
        print(self.var)
Run Code Online (Sandbox Code Playgroud)

我遇到了问题,我正在寻找一种方法来使实例变量的类型提示成为可能。我当然可以使用类型提示参数,def __init__(self, var: str):但这不会影响实例变量本身。

然后我注意到在一些描述中(如这里),他们使用术语实例变量来表示var这样的:

class MyClass:
    var : str = 'hello'

    def __init__(self, var : str = None):
        self.var = var if var
        print(self.var)
Run Code Online (Sandbox Code Playgroud)

这确实是解决方案,但这仍然是一个实例变量吗?因为它是在类体中定义的,所以在我的理解中它将是一个类变量。如果您要为 var 使用列表,则对该列表变量的所有更改都将通过实例共享。

但在这种情况下不会有问题,因为字符串被替换并且不会被其他实例共享。但是,如果您将其称为实例变量,对我来说似乎是错误的,而我不知道是否应该像这样使用它只是为了让类型提示起作用。

python type-hinting

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

带有一些强制键的字典作为函数输入

我有一个函数,它有一个字典作为参数.我将传递各种词典,其中包含的条目多于函数内部使用的几个.另外,我想在函数定义中看到需要哪些键.所以我写

def fun(indict=dict(apple=None, pear=None)):
Run Code Online (Sandbox Code Playgroud)

但是,该函数现在接受任何输入为indict.是否有一种聪明的写作方式

any dictionary that has at least the keys 'apple' and 'pear' is accepted.
Run Code Online (Sandbox Code Playgroud)

就像是

def fun(indict=dict(apple=NeedsToBeSpecified, pear=NeedsToBeSpecified)):
Run Code Online (Sandbox Code Playgroud)

python dictionary

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

标签 统计

python ×2

dictionary ×1

type-hinting ×1