Skip to main content
 首页 » 编程设计

python之在类中编写代码和在 Python 中 def __init__(self) 中编写代码有什么区别

2025年05月04日18langtianya

<分区>

Possible Duplicate:
Variables inside and outside of a class __init__() function

我知道当一个类被调用时,它会先运行 __init__ 中的代码。我仍然看不出这与直接在类下编写代码之间的区别。

例如:

class main(): 
  x = 1 
 
  def disp(self): 
    print self.x 
class main(): 
  def __init__(self): 
    self.x = 1 
 
  def disp(self): 
    print self.x 

对我来说,两者具有相同的功能。 (也许我遗漏了什么。)我想知道哪个更(咳咳)pythonic 以及为什么。