除了名字以外,这些类之间有什么不同吗?
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'
如果跟踪类和实例字典,这很容易理解。
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键值对在里面。
这是关于特定变量的所有信息。
类就像创建对象的蓝图。让我们用建房子来做个比喻。你有房子的蓝图,所以你可以建造房子。你可以在资源允许的情况下建造尽可能多的房子。
在这个比喻中,蓝图是类,房子是类的实例化,创建一个对象。
这些房子有共同的属性,比如有屋顶、客厅等。这就是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'