13

それとも、別の方法で宣言できますか?

以下のコードは機能しません。

class BinaryNode():
    self.parent = None
    self.left_child = None

で宣言する必要があり__init__ますか?

4

4 に答える 4

13

で宣言する必要はありませんが、__init__を使用してインスタンス変数を設定するにはself、 への参照が必要でありself、変数を定義している場所にはありません。

でも、

class BinaryNode():
    parent = None
    left_child = None

    def run(self):
        self.parent = "Foo"
        print self.parent
        print self.left_child

出力は次のようになります。

Foo
None

コメントであなたの質問に答えるには、はい。私の例では、次のように言えます。

bn = BinaryNode()
bn.new_variable = "Bar"

または、先ほど示したように、クラス レベルの変数を設定することもできます。クラスのすべての新しいインスタンスは、インスタンス化時にクラス レベル変数のコピーを取得します。

おそらく、コンストラクターに引数を渡すことができることに気付いていないでしょう。

class BinaryNode(object):

    def __init__(self, parent=None, left_child=None):
        self.parent = parent
        self.left_child = left_child



bn = BinaryNode(node_parent, node_to_the_left)
于 2012-09-05T03:40:48.907 に答える
2

いいえ。@property私はこのことのための変数が大好きです:

class Data(object):
    """give me some data, and I'll give you more"""
    def __init__(self, some, others):
        self.some   = some
        self.others = others

    @property
    def more(self):
        """you don't instantiate this with __init__, per say..."""
        return zip(self.some, self.others)


>>> mydata = Data([1, 2, 3], ['a', 'b', 'c'])
>>> mydata.more
[(1, 'a'), (2, 'b'), (3, 'c')]
于 2012-09-05T03:48:11.880 に答える
0

また、クラス レベルの変数を使用することもできますが、私はそれらをクラス定数と呼んでいます。

class Connection(object):
    """helps you connect to the server at work"""
    YOUR_IP = '10.0.9.99'

    def __init__(self, username, password):
        self.ip = Connection.YOUR_IP
        self.un = username
        self.pw = password

    #...and so on
于 2012-09-05T03:52:48.460 に答える