除了名字以外,这些类之间有什么不同吗?

class WithClass ():
    def __init__(self):
        self.value = "Bob"
    def my_func(self):
        print(self.value)

class WithoutClass ():
    value = "Bob"

    def my_func(self):
        print(self.value)

如果我使用或不使用__init__方法来声明变量值,会有任何区别吗?

我主要担心的是,我只会以一种方式使用它,而这会给我带来更多的问题。


当前回答

在__init__之外设置的变量属于类。它们由所有实例共享。

在__init__(以及所有其他方法函数)中创建并以self为前缀的变量。属于对象实例。

其他回答

示例代码:

class inside:
    def __init__(self):
        self.l = []

    def insert(self, element):
        self.l.append(element)


class outside:
    l = []             # static variable - the same for all instances

    def insert(self, element):
        self.l.append(element)


def main():
    x = inside()
    x.insert(8)
    print(x.l)      # [8]
    y = inside()
    print(y.l)      # []
    # ----------------------------
    x = outside()
    x.insert(8)
    print(x.l)      # [8]
    y = outside()
    print(y.l)      # [8]           # here is the difference


if __name__ == '__main__':
    main()

如果跟踪类和实例字典,这很容易理解。

class C:
   one = 42
   def __init__(self,val):
        self.two=val
ci=C(50)
print(ci.__dict__)
print(C.__dict__)

结果是这样的:

{'two': 50}
{'__module__': '__main__', 'one': 42, '__init__': <function C.__init__ at 0x00000213069BF6A8>, '__dict__': <attribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}

注意,我在这里设置了完整的结果,但重要的是,实例ci字典将只是{'two': 50},类字典将有'one': 42键值对在里面。

这是关于特定变量的所有信息。

正如S.Lott所指出的,

在init之外设置的变量属于该类。它们由 所有实例。 在init(和所有其他方法函数)中创建的变量和 以自我开头。属于对象实例。

然而, 注意,类变量可以通过self访问。<var>,直到它们被一个具有类似名称的对象变量所掩盖。<var>在给它赋值之前将返回Class的值。<var>但之后它将返回obj。< var >。这里有一个例子

In [20]: class MyClass: 
    ...:     elem = 123 
    ...:  
    ...:     def update(self,i): 
    ...:         self.elem=i  
    ...:     def print(self): 
    ...:         print (MyClass.elem, self.elem) 
    ...:  
    ...: c1 = MyClass()  
    ...: c2 = MyClass() 
    ...: c1.print() 
    ...: c2.print()                                                                                                                                                                                                                                                               
123 123 
123 123 
In [21]: c1.update(1) 
    ...: c2.update(42) 
    ...: c1.print() 
    ...: c2.print()                                                                                                                                                                                                                                                               
123 1 
123 42
In [22]: MyClass.elem=22 
    ...: c1.print()  
    ...: c2.print()                                                                                                                                                                                                                                                               
22 1 
22 42

第二个注意事项:考虑插槽。它们可能提供了更好的实现对象变量的方法。

类就像创建对象的蓝图。让我们用建房子来做个比喻。你有房子的蓝图,所以你可以建造房子。你可以在资源允许的情况下建造尽可能多的房子。

在这个比喻中,蓝图是类,房子是类的实例化,创建一个对象。

这些房子有共同的属性,比如有屋顶、客厅等。这就是init方法的作用。它用你想要的属性构造对象(房子)。

让我们假设你有:

`class house:`
`roof = True`
`def __init__(self, color):`
`self.wallcolor = color`

>>创建小金锁的房子:

>> goldlock = house() #() invoke's class house, not function

>> goldlock.roof

>> True

all house's have roofs, now let's define goldlock's wall color to white:

>> goldlock.wallcolor = 'white'
>>goldlock.wallcolor
>> 'white'

在__init__之外设置的变量属于类。它们由所有实例共享。

在__init__(以及所有其他方法函数)中创建并以self为前缀的变量。属于对象实例。