Can a class variable be an instance of the class?

前端 未结 2 740
醉梦人生
醉梦人生 2021-01-26 23:07

Can a class variable of say, class Foo be a Foo object itself?

For example, I\'m trying to build a class for the finite field of order 11, and

相关标签:
2条回答
  • 2021-01-26 23:53

    You can do something like this:

    class FiniteField11:
       def __init__(self, element):
           self.elt = element
    FiniteField11.generator = FiniteField11(2)
    

    Your code fails because FiniteField11 was not defined when the class defintion was parsed.

    0 讨论(0)
  • 2021-01-27 00:13

    Yes it can, but the name doesn't exist until the class statement finishes. Therefore, you have to set this class variable after creating the class, perhaps just below the class block or in the instance initializer.

    0 讨论(0)
提交回复
热议问题