【发布时间】:2014-03-24 04:43:56
【问题描述】:
好的。所以我看到有人在使用这个代码,我理解它,所以我将使用它。
有必要有__init__吗?
class A(object):
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print self.x + ' ' + foo
a = A()
a.method_a('Sailor!')
我不能这样做吗:
class A(object):
def method_a(self):
print "Hello, Sailor!"
a = A()
print a.method_a()
当我这样做时,我会听到“你好,水手!”但我在它下面得到一个“无”?这与__init__ 有关吗?有人解释一下。
【问题讨论】:
-
None与类/初始化问题无关,只是因为您的method_a()没有返回值。希望这能在一定程度上减少混乱。 -
如果你忽略它,你的类的
__init__就是继承自object的那个(它什么都不做)。没关系。 -
从
print a.method_a()中省略print,而None你将不再拥有。