Monday 15 August 2011

Global vars in python -


I currently have some class fu () with some variables that are not shared in all instances of Fu Class only, Rather also by the other class bar.

or

  class foo (): __init __ (self, a, b): self. A = A self. B = B square bar (): __int __ (self, A, B): self. A = one will be .b = b   

One solution will be to create variables of one and B class, but how can I do this during cleaning? Can I put both classes in the same file and give them reference to some global variable A and B? Is this bad behavior?

Since you have not given your intent or real world situation, so the variables reach just for some variables Share.

The first option: Global.

  a = b = no square foo (): def __init__ (self, _a, _b): global a, ba, b = _ a, _ b square bar (): def __init __ (Auto, _a, _b): global a, ba, b = _a, _b   

second option: foo class wars

  square foo (): A = b = any def __init __ (self, a, b): foo.a, foo.b = a, b square bar (): DEF __init __ (self, a, b): foo.a , Foo.b = a, b   

3 options: legacy

  class foo (): def __init __ (self, a, b): self . A, self B = A, B square bar (FU): pass   

4 options: external class

  class exterior (): a = b = any class Foo (): def __init __ (self, a, b): external.a, outer.b = a, b square bar (): def __init __ (self, a, b): external.a, external.b = A, B   

5th option: compsition

  square foo (): def __int_ (self, A, B): self. A, self B = A, B class bar (): def __init __ (self, a, b): self.foo = foo (a, b)   

6 Option: External function on local variables Termination

  def external (): a = b = any square foo (): def __init __ (auto, _a, _b): nonlocal a, ba, b = _a, _b class bar (): Def __init __ (self, _a, _b): nonlocal a, ba, b = _a, _b, #things with foo and bar   

7th option: foo Completion of the __init __ local variable

  square foo (): def __init __ (self, a, b): self. A, self.b = a, b square bar (): nonlocal a, b #do things with another b directly: self.bar = bar ()    

No comments:

Post a Comment