Does Python have class prototypes (or forward declarations)?

前端 未结 6 1757
不思量自难忘°
不思量自难忘° 2020-11-28 10:06

I have a series of Python classes in a file. Some classes reference others.

My code is something like this:

class A():
    pass

class B():
    c = C         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 10:14

    In Python you don't create a prototype per se, but you do need to understand the difference between "class attributes" and instance-level attributes. In the example you've shown above, you are declaring a class attribute on class B, not an instance-level attribute.

    This is what you are looking for:

    class B():
        def __init__(self):
            self.c = C()
    

提交回复
热议问题