开发者

declaring empty class member in python

开发者 https://www.devze.com 2022-12-14 19:47 出处:网络
i am trying to read a tree structure file in python. I created a class to hold the tree objects. One of the members

i am trying to read a tree structure file in python. I created a class to hold the tree objects. One of the members should hold the parent object. Since the parentObject member is of the same type as the class itself, I need to declare this as an empty variable of type "self".

How do 开发者_运维知识库I do that in python?

Thank you very much for your help.


Since the parentObject member is of the same type as the class itself, I need to declare this as an empty variable of type "self".

No, you do not need to declare anything in Python. You just define things.

And self is not a type, but the conventional name for the first parameter of instance methods, which is set by the language to the object of the method.

Here's an example:

class Tree(object):

    def __init__(self, label=None):
        self.label = label
        self.parent = None
        self.children = []

    def append(self, node):
        self.children.append(node)
        node.parent = self

And here's how that could be used:

empty_tree = Tree()

simple_tree = Tree()
simple_tree.append(Tree('hello'))
simple_tree.append(Tree('world'))


In Python, you don't declare variables as having any type. You just assign to them. A single variable can be assigned objects of different types in succession, if you wanted to do so. "self" is not the type but a naming convention used to refer to the current object, like "this" in Java / C++ (except in Python you could call it anything you wanted).


I assume that for the root node, you want such an object. It's much more Pythonic to say:

self.parent = None

in your root object, than to create an empty object of type self.__class__. For every other node object in the tree, self.parent should refer to the actual parent node.

Remember, in Python you don't have 'variables', you have objects, and there is no need for self.parent to be of same type in all the instances of a class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号