newbie question re classes and self
__peter__ at web.de
Tue Mar 28 05:09:18 EDT 2017
> 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):
>>> 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
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()
If neither is what you want please give a concrete example or a more
detailed plain-english description.
More information about the Python-list