0

I want to access an instance var from a class outside the __init__, but I'm getting stuck!

 import sys

class Borg(object):
    __shared_state = {}
    def __init__(self, nombre):
        self.__dict__ = self.__shared_state
        self.nombre = nombre 

        print 'my instance vr::', self.nombre

        # panga = 'pangas'  

    panga = 'pangas'


    print 'te copio con  ' 


    print panga

    #print self.nombre


pingus = Borg('varString')


print pingus.nombre

If I uncomment print self.nombre, I get that "self.nombre is not recognized"?

How do I access this var?

1
  • 1
    Your indentation appears to be messed up, because you're executing print statements inside a class definition. (and the indentation of import sys is wrong, too.) Commented Mar 31, 2012 at 14:23

3 Answers 3

4

This may work better. You should encapsulate that code in a method, like:

import sys

class Borg(object):
    __shared_state = {}
    def __init__(self, nombre):
        self.__dict__ = self.__shared_state
        self.nombre = nombre 

    def instance_method_1(self):
        print 'my instance vr::', self.nombre
        panga = 'pangas'
        print 'te copio con  ' 
        print panga
        print self.nombre


pingus = Borg('varString')


print pingus.nombre
pingus.instance_method_1()
Sign up to request clarification or add additional context in comments.

Comments

1

You can't have free standing code in a python class. You could access self.nombre from another method.

  def foo(self):
     print self.nombre

1 Comment

Well, you can have free-standing code in a Python class, but it will be executed when the class is defined, not when it is instantiated. At this point, self is not defined.
0

When you are calling

print self.nombre

The object is not constructed yet (there is no instance of Borg when that statement is evaluated) so there is no self nor nombre. If you want to access nombre you first need to construct the object:

pingus  = Borg("varString")

and then access nombre:

print pingus.nombre

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.