In my code I have a class that contain a lot of functions and a pair of classes (subclass I think). The main problem is that I want the subclasses to call an object, defined in the function init and I don't know ho to referencing it
The main issue in code:
class principal:
def __init__(self):
self.a = object()
...
...
class secondary(threading.Thread):
def __init__(self):
a.proceed() # problem !!!
I've tried to call a like principal.a.proceed() but the Traceback tells me: AttributeError: class principal has no attribute 'a'
how can I solve this. It appear that it is something easy to solve, but I can't see it.
You have to instantiate a principal object in the
__init__
forsecondary
and then reference the a object
Note that my variables names are horrendous
Note too that you're not subclassing
principal
, you're subclassingthreading.Thread
. Indenting isn't enough, you have to include the superclass in the class definitionUnlike Java, there will not be a new
principal.secondary
class for each instance ofprincipal
. When you declare a class inside another class (a classeption :P) in Python it only means that the inside class will be accessed as a class attribute of the outside class and nothing more. So, there is no outside instance ofprincipal
to be accessed from theprincipal.secondary
methods.Indeed, you want to do something meaningless in Python. I would suggest you do whatever you are trying to do by some other way. For example, you can get an instance of
principal
and pass it as parameter for the constructor ofprincipal.secondary
:Also, note that
principal.secondary
is not a subclass ofprincipal
but only a class inside a class. "Subclasses" are classes that extends/inherits from another one. So,principal.secondary
is a subclass ofthreading.Thread
, not from principal.Finally, two little off-topic suggestions: always make your classes extend
object
if it does not extend any other class and follow the PEP-8 by starting the name of your classes by an uppercase letter:EDIT: If you really want to have a class bound to an instance like in Java (and I doubt you want),there is a way to emulate it. Create a function that receives an object as parameter, declare and return the class:
The
outerObject
parameter will be bound to the class declared inside the function.Now, declare your
Principal
class. Call thegenerateSecondary()
function in the__init__
method ofPrincipal
passing the initializing object as parameter and setting it to an attribute of the initializing object:The result is:
It is possible because Python classes are first-class objects that can be bound to closures (in the traditional sense of "closure"). I do not recommend to use such code but there is a way to do what you asked - which may not be what you need.