简体   繁体   中英

Create instance of a class as a static variable

I want to create an instance of a class as a static variable of the class.

For example:

class Complex:
    I = Complex(0, 1)
    def __init__(self, x, y):
        self.x = x
        self.y = y

When I do that, I get NameError: name 'Complex' is not defined . How can I do that?

Try call outside

class Complex:
  def __init__(self, x, y):
    self.x = x
    self.y = y
I = Complex(0, 1)

__init__ אין לך סיבה לקרוא לאותו קלאס, כיוון שהקלאס אוטומטית מריץ את ה

You have no reason to call the class inside, because the class automatically runs the __init__

Try to instance the class after the class definition:

class Complex: 

  def __init__(self, x, y): 
     self.x = x 
     self.y = y
I = Complex(0, 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM