-1

Is there is some python rule that says declare/define all global variable in the "init" method? Why would python allow this?

for example, see the following code:

class Myclass():
  def __init__(self,input):
      self.input = input
  def a_method(self):
      self.sneaky = {}
      local_var = 'a var'
      return local_var
  def another_method(self):
      print self.input
      print self.sneaky, ', O sneaky you bad var'
      return

If my class had many methods the variable 'self.sneaky' would have been hard to spot. And "a_method" has to be called first other wise AttributeError is raised when "another_method" is called. I just spotted it in somebody's code and want to know if it is common practice.

2

1 Answer 1

1

First of all, you're not talking about global variables, but about instance variables. Then whether or not declaring variables in a method or in the constructor depends on the scenario you're using.

Basically, the only rule that prevail is to always declare a variable before using it. (or you will get the AttributeError exception).

Usually, it's a good idea to declare all members of your class in init, so you can work on the assumption they exist with a default value. Though, sometimes you may prefer to defer the creation of the class type, and the attribution of the elements within.

A good example would be if within a loop you create a million instances, but then you only select a few of those to work with at a given time. Then you may want to have the constructor be as simple as possible with what's needed at instanciation, and create a populate() method that you call just before using it to add the default members you're about to use. That pattern is often seen in building graphical UIs.

HTH

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.