问题
In Python, can you have classes with members that are themselves pointers to members of the type of the same class? For example, in C, you might have the following class for a node in a binary tree:
struct node {
int data;
struct node* left;
struct node* right;
}
How would you equivalently create this in python?
回答1:
Python is a dynamic language. Attributes can be bound at (almost) any time with any type. Therefore, the problem you are describing does not exist in Python.
回答2:
Emulating a C struct in Python (using str instead of int as the data type):
"Declaration":
class Node(object):
data = None # str
left = None # Node object or None
right = None # Node object or None
Usage:
root = Node()
root.data = "foo"
b = Node()
b.data = "bar"
root.left = b
z = Node()
z.data = "zot"
root.right = z
回答3:
How would I equivalently create this in python?
class node( object ):
def __init__( self, data, left, right ):
self.data = data
self.left = left
self.right = right
Since all Python variables are, in effect, typeless references, you don't have to mention up front that left and right are going to be instances of nodes.
回答4:
You can't declare types in Python - therefore, there are no problems declaring types in Python.
回答5:
http://code.activestate.com/recipes/286239-binary-ordered-tree/ is a sample binary tree created using that structure.
回答6:
While this, as other answers have pointed out, is not a problem due to the dynamic typing, in fact, for Python3, this is a very real issue when it comes to type annotations. And this will not work (note a type annotation of the method argument):
class A:
def do_something_with_other_instance_of_a(self, other: A):
print(type(other).__name__)
instance = A()
other_instance = A()
instance.do_something_with_other_instance_of_a(other_instance)
results in:
def do_something_with_other_instance_of_a(self, other: A):
NameError: name 'A' is not defined
more on the nature of a problem here: https://www.python.org/dev/peps/pep-0484/#the-problem-of-forward-declarations
although there is a workaround: Self-reference or forward-reference of type annotations in Python, personally, I think that its non-elegance may render it inacceptable in some cases.
Personally, I ended up NOT using python3-style type annotation in such cases, but, for the sake of getting autocompletion in my IDE (PyCharm), I use docstrings like this:
Update: alternatively, instead of using docstrings, you can use "type: " annotations in a comment. This will also ensure that mypy static type checking will work (mypy doesn't seem to care about docstrings):
来源:https://stackoverflow.com/questions/3877947/self-referencing-classes-in-python