newbie question re classes and self

Peter Otten __peter__ at web.de
Tue Mar 28 05:09:18 EDT 2017


loial wrote:

> Can I pass self(or all its variables) to a class?
> 
> Basically, how do I make all the variables defined in self in the calling
> python script available to the python class I want to call?

Inside a method you can access attributes of an instance as self.whatever:

>>> class A:
...     def foo(self):
...         self.bar = 42
...     def baz(self):
...         print(self.bar)
... 
>>> a = A()
>>> a.baz() # bar attribute not yet set
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in baz
AttributeError: 'A' object has no attribute 'bar'
>>> a.foo() # sets bar
>>> a.baz() # successfully print the newly created bar attribute
42

The class itself has no access to bar. In the rare case where you want to 
share data between instances you can use a class attribute:

>>> class B:
...     bar = 42
... 
>>> x = B()
>>> y = B()
>>> x.bar
42
>>> y.bar
42

If neither is what you want please give a concrete example or a more 
detailed plain-english description.



More information about the Python-list mailing list