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

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__方法来声明变量值,会有任何区别吗?

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


当前回答

没有自我

创建一些对象:

class foo(object):
    x = 'original class'

c1, c2 = foo(), foo()

我可以改变c1实例,它不会影响c2实例:

c1.x = 'changed instance'
c2.x
>>> 'original class'

但是如果我改变了foo类,该类的所有实例也会被改变:

foo.x = 'changed class'
c2.x
>>> 'changed class'

请注意Python作用域是如何工作的:

c1.x
>>> 'changed instance'

与自我

改变类不会影响实例:

class foo(object):
    def __init__(self):
        self.x = 'original self'

c1 = foo()
foo.x = 'changed class'
c1.x
>>> 'original self'

其他回答

在__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键值对在里面。

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

试试这个,看看有什么不同

class test:
    f = 3

    def __init__(s, f):
        s.__class__.f = f
        s.f = s.__class__.f
        print(f'def __init__(s, {f})')
        print(f's.__class__.f = {f}')
        print(f's.f={s.__class__.f}')
        print(f'f={f}')
        print('===============init over===========')

    def setinstancetoOne(s, f):
        print(f'def setinstancetoOne(s, {f})')
        s.f = f

    print(f'class var f = {f}')

    def useClassname(test):
        print(f'>>>>def useClassname({test})')
        print(f'test.f {test.f}')

    def p_method(s):
        print(f'>>>>def p_method({s})')
        print(f's.f {s.f}')
        print(f'test.f {test.f}')
        print(f's.__class__.f {s.__class__.f}')

    print(f'class var f={f}')


# test.__init__.f = 19
t = test(2)
t.useClassname()
t.p_method()
print(f'Outside class t.f {t.f}')
print(f'Outside class test.f {test.f}')

print('______difference__________')
t = test(2)
t.setinstancetoOne(1)
t.useClass()
t.p_method()
print(f'Outside class instance variable(2) {t.f}')
print(f'Outside class class variable(3) {test.f}')

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

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

这些房子有共同的属性,比如有屋顶、客厅等。这就是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'