简体   繁体   English

如何在 class 内的 python __init__ 中使用变量

[英]How to use variable in python __init__ inside the class

Consider the following code: i have a class named X. this class is initialised with some an initial value.考虑以下代码:我有一个名为 X 的 class。这个 class 用一些初始值初始化。 In the class, I want to initiate queue data structure with the initvalues of the class.在 class 中,我想用 class 的 initvalues 启动队列数据结构。 Since this queue will be used later in many other functions in the class and it needs to have elements.由于此队列稍后将在 class 中的许多其他功能中使用,因此它需要具有元素。 Here we cant use initvalues since an error is shown.在这里,我们不能使用 initvalues,因为会显示错误。 How can I do this?我怎样才能做到这一点? thank you谢谢你

class X :
def __init__(self, initvalues):
        self.initvalues=initvalues

queue= dequeu(initivalues)

initivalues is an attribute of class X . initivalues是 class X的一个属性。 In order to access this attribute, you have to call it through its class.为了访问这个属性,你必须通过它的 class 来调用它。 Try to change queue= dequeu(initivalues) to queue= dequeu(X.initivalues) .尝试将queue= dequeu(initivalues)更改为queue= dequeu(X.initivalues)

To be clear, initvalues is not a class attribute, it is an instance attribute of the class.需要明确的是, initvalues不是 class 属性,它是 class 的实例属性。 Put another way, it is only accessible through instances of class X , not through class X itself.换句话说,它只能通过 class X的实例来访问,而不是通过 class X本身。

Example:例子:

from collections import deque
class X:
    def __init__(self, initvalues):
        self.initvalues=initvalues

one_x = X([1, 2, 3])

queue= deque(one_x.initvalues)

print(queue)

Output: Output:

deque([1, 2, 3])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM