Reputation: 175
I come from a MATLAB background. When I create class definitions, I can instantiate "empty" variable names and then later assign values or objects to them. I.e.
classdef myclass < handle
properties
var1
var2
end
end
a = myClass;
a.var1 = someOtherClassObject;
How do I do this in Python? I tried something like this:
class myClass:
def __init__(self):
var1
var2
a = myClass()
a.var1 = someOtherClassObject()
But that's not correct. The main purpose is to build a definition of my class, like a structure, and then later go and instantiate the variables as needed.
And help would be appreciated.
Upvotes: 10
Views: 23684
Reputation: 31
The accepted answer does not consider type-checking.
The answer would not work properly if the variable has a type, because None is a different type.
You could leverage python class variable and instance variable logic(When you create a class variable and updates it self.variable
it becomes an instance variable).
With this method when you introduce types linters would not complain of None
types.
Upvotes: 3
Reputation: 10298
There is no such thing as "unitialized variables" in Python as you have in MATLAB, because they are not necessary. If you want to add variables to a class instance later, just add them:
>>> class myclass:
>>> pass
>>>
>>> a = myclass()
>>> a.var1 = 5
>>> a.var1
5
You can also add them directly to the class, so they appear in all instances of the class. This also adds them to instances of the class created earlier, so it can be dangerous if you aren't careful:
>>> class myclass:
>>> pass
>>>
>>> a = myclass()
>>> a.var1
AttributeError: 'myclass' object has no attribute 'var1'
>>>
>>> myclass.var1 = 5
>>> a.var1
5
You don't want to do this in MATLAB because you have to use addprop
to add it first, which is needlessly complicated. Python is a more dynamic language than MATLAB in many cases. Rather than initializing something, then doing it, in Python you just do it.
Technically they are not "variables", in Python they are called "attributes" and in MATLAB they are called "properties" (Python has something called properties, but they are not the same as properties in MATLAB).
Upvotes: 1
Reputation: 90889
You need to use self.
to create variables for instances (objects)
I do not think you can have an uninitialized name in python, instead why not just initialize your instance variables to None
? Example -
class myClass:
def __init__(self):
self.var1 = None
self.var2 = None
You can later go and set them to whatever you want using -
a = myClass()
a.var1 = someOtherClassObject
If you need to define class variables (that are shared across instances) , you need to define them outside the __init__()
method, directly inside the class as -
class myClass:
var1 = None
var2 = None
def __init__(self):
pass
Upvotes: 19