关于Classes和init方法

时间:2013-03-16 07:22:09

标签: python

我刚刚开始编码,并且在使用OOP和类部分时遇到了绊脚石。我们总是需要__init__方法吗?如果不是,我们何时不需要它?

1 个答案:

答案 0 :(得分:2)

不,你不是被迫写一个。 当你在初始时实际设置变量及其值时,你只需要一个......

那就是说,在99%的情况下,你想设置传递给你的变量,或者甚至是某些默认值......

class A(object):
    pass

class B(object):
    def __init__(self, foo):
        self.foo = foo

someA = A() #creates an object of type A, with no custom variables or methods
someB = B('bar') #creates an object of type B, in which foo is set

注意,从object继承称为新样式类,应该完成。这不是强制性的......

相关问题