我是Python的新手 - 只是想更好地理解某些事情背后的逻辑.
为什么我会这样写(默认变量是__init__):
class Dawg:
def __init__(self):
self.previousWord = ""
self.root = DawgNode()
self.uncheckedNodes = []
self.minimizedNodes = {}
def insert( self, word ):
#...
def finish( self ):
#...
Run Code Online (Sandbox Code Playgroud)
而不是这个:
class Dawg:
previousWord = ""
root = DawgNode()
uncheckedNodes = []
minimizedNodes = {}
def insert( self, word ):
#...
def finish( self ):
#...
Run Code Online (Sandbox Code Playgroud)
我的意思是 - 为什么我需要使用__init__- >如果我可以直接将默认变量直接添加到类中?
the*_*eye 14
当你在Class中创建变量时,它们是类变量(它们对于类的所有对象都是通用的),当你初始化变量时__init__,self.variable_name = value它们是按实例创建的,并且被称为实例变量.
例如,
class TestClass(object):
variable = 1
var_1, var_2 = TestClass(), TestClass()
print var_1.variable is var_2.variable
# True
print TestClass.variable is var_1.variable
# True
Run Code Online (Sandbox Code Playgroud)
由于变量是类变量,因此is运算符求值为True.但是,在实例变量的情况下,
class TestClass(object):
def __init__(self, value):
self.variable = value
var_1, var_2 = TestClass(1), TestClass(2)
print var_1.variable is var_2.variable
# False
print TestClass.variable is var_1.variable
# AttributeError: type object 'TestClass' has no attribute 'variable'
Run Code Online (Sandbox Code Playgroud)
并且您只能使用类名来访问实例变量.
| 归档时间: |
|
| 查看次数: |
1955 次 |
| 最近记录: |