Access from class variable to one on constructor

K

Kless

How to access from a class variable to one that is initialized on the
constructor?
--------------
class Foo():
foo = bar # I want to access *from here* to variables created on
the constructor.

def __init__(self, bar_init):
self.bar = bar_init
 
G

Gabriel Genellina

How to access from a class variable to one that is initialized on the
constructor?
--------------
class Foo():
foo = bar # I want to access *from here* to variables created on
the constructor.

def __init__(self, bar_init):
self.bar = bar_init
--------------

Unless I misunderstand you, you can't do that. Class variables are shared
by all instances and don't depend on a particular instance - they exist
even *before* any instance is created.
Note: I've to create a subclass where the parent class to get
variables using *for i in dir(self): * so it doesn't get variables
initialized on the constructor.

This part I don't understand at all. Perhaps a concrete example, showing
what you actually want at the end?
 
S

Steven D'Aprano

Unless I misunderstand you, you can't do that. Class variables are
shared by all instances and don't depend on a particular instance - they
exist even *before* any instance is created.


Please don't use the term "class variables" to mean class *attributes*,
it makes my brain hurt. If a string variable is a string, and an int
variable is an int, and a bool variable is a bool, a class variable
should be a class.

What you can do is shift the creation of the class attribute to the
constructor, instead of when the class is created:

class Spam():
def __init__(self, bar_init):
self.__class__.foo = bar_init



But I'm not sure why you would want to.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top