Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to declare uninitialized variable in class definition in python

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.

like image 412
userJohn Avatar asked Jul 17 '15 01:07

userJohn


People also ask

How do you declare a variable inside a class in Python?

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.

How do you declare an empty class variable in Python?

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.

How do you declare a variable as nothing 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.


1 Answers

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
like image 102
Anand S Kumar Avatar answered Sep 17 '22 18:09

Anand S Kumar