1

I'm new at Python and I'm trying to do something and hope you can help me:
If I'm defining a class at Python like: class foo:, and inside the class I want to do something with "foo" object, i.e. - I want that one of the objects of the class will be something like a=foo().

So, it should look like:

 class foo:
     def __init__(self):
         self.t=7

     a=foo() #it's outside init....

It is possible? There is a way to do it?
(I'm trying to do this and it's always give me errors...)
(I tried to do import to the file but it doesn't help at all...)

Thank you!

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Yoar
  • 183
  • 8

2 Answers2

1

Do it after the class definition:

class Foo:
    pass

Foo.a = Foo()
kindall
  • 178,883
  • 35
  • 278
  • 309
  • Yes, it's an attribute of the class, just as if you had defined it in the class definition. – kindall Dec 04 '16 at 19:05
  • `NameError: name 'foo' is not defined` – Yoar Dec 04 '16 at 19:36
  • Ah yeah, you musta caught my answer in the brief window while I had that typo in it. As to your other comment, yeah, it's part of the class; see for yourself! – kindall Dec 04 '16 at 20:30
0

No. at the stage you define a = foo, foo is not defined. However, you can create a variable for foo instance inside foo like:

class Foo:
  def __init__(self):
    pass

  a = None

Foo.a = Foo()

edited according to the comments.

interjay
  • 107,303
  • 21
  • 270
  • 254
Musen
  • 1,244
  • 11
  • 23