Kevin
Kevin

Reputation: 794

Can a class variable be an instance of the class?

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 I want a chosen generator (2) to be associated with this class an instance.

What I have in mind:

class FiniteField11:
   generator = FiniteField11(2)

   def __init__(self, element):
       self.elt = element

This does not compile; I have a NameError: name 'FiniteField11' is not defined. I realize that there is a chicken-or-egg first problem here, but is there a way to achieve what I want?

Apologies if this is a duplicate, but I can't find one.

Upvotes: 1

Views: 93

Answers (2)

Yann Vernier
Yann Vernier

Reputation: 15887

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.

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251106

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.

Upvotes: 3

Related Questions