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.
In Python, Class variables are declared when a class is being constructed. They are not defined inside any methods of a class because of this only one copy of the static variable will be created and shared between all objects of the class.
In Python, you can create an empty class by using the pass command after the definition of the class object, because one line of code is compulsory for creating a class. Pass command in Python is a null statement; it does nothing when executes. The following is an example of an empty class object in Python.
In order to define a null variable, you can use the None keyword. Note: The None keyword refers to a variable or object that is empty or has no value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With