How to declare an attribute in Python without a value?


In this article, we will show you how to declare an attribute in python without a value.

In Python, as well as in several other languages, there is a value that means "no value". In Python, that value with no value is None, let us see how it is used.

You simply cannot. Variables are just names in Python. A name always refers to an object ("is bound"). It is conventional to set names that do not yet have a meaningful value but should be present to None.

Method 1: By Initializing them with None Directly

We can directly assign the attributes with the None value. By creating a class and initializing two variables within the class with None.

# creating a class with the name Student class Student: # initiaizing the values of instance variables with None StudentName = None RollNumber = None

Those are like instance variables though, and not class variables, so we may as well write

Instead of writing them as above, we can use the self keyword to instantiate the instance variables within the constructor init__() method(In Python, __init__ is one of the reserved methods. It is referred to as a constructor in object-oriented programming. When an object is created from the class and access is necessary to initialize the class's attributes, the __init__ function is called).

Here the self is used to point to the instance variables(The self represents the instance of the class. It binds the properties with the arguments provided. We use self because Python does not use the '@' syntax to refer to instance attributes))

Example

# creating a class with the name Student class Student(object): # creating a init constructor def __init__(self): # initiaizing the values of instance variables with None self.StudentName = None self.RollNumber = None

Method 2

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a class with the name Student .

  • Create an __init__ constructor by passing the StudentName, and RollNumber as arguments to it.

  • Inside the constructor, initialize the values of instance variables using the self attribute (The self represents the instance of the class. It binds the properties with the arguments provided).

  • Create an object of the Student class by passing StudentName, and RollNumber arguments values as None and calling it.

  • Print the value of the StudentName attribute using the above student class object.

  • Print the value of the RollNumber attribute using the above student class object using the (.) symbol. Here (.) symbol is used to access the attribute.

Example

# creating a class with the name Student class Student(object): # creating an init constructor by passing the StudentName, and RollNumber as arguments to it def __init__(self, StudentName, RollNumber): # initiaizing the values of instance variables self.StudentName = StudentName self.RollNumber = RollNumber # creating an object of the Student class by passing # StudentName, RollNumber values as None and calling it studentObj= Student(None, None) # printing the value of the StudentName attribute print('The value of the StudentName attribute is:',studentObj.StudentName) # printing the value of the roll number attribute print('The value of the RollNumber attribute is:',studentObj.RollNumber)

Output

The value of the StudentName attribute is: None
The value of the RollNumber attribute is: None

Method 3

Why do we need to Initialize the attributes?

Let us answer this question by Printing the values of the instance attributes without assigning them any value

Example

class Student: StudentName RollNumber print(StudentName, RollNumber)

Output

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    class Student:
  File "main.py", line 2, in Student
    StudentName
NameError: name 'StudentName' is not defined

StudentName and RollNumber and print(StudentName, RollNumber) are parsed as expressions. You get a NameError since they haven't been assigned yet.

A variable in Python must be defined using an assignment statement before it can be used in an expression; otherwise, a NameError is returned. It's worth noting that "before" here refers to "execution order," not "source code order." There's more to it (import statements, globals, namespace hacks), but we'll keep things easy for now.

To define a variable "without a value," simply assign it the value None which is the idiomatic way

Also, your code appears to be looking for instance members rather than class members. Some static analysis tools, such as pylint, recognize the idiomatic approach to accomplish it as follows:

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Inside the constructor, initialize the values of instance variables with None using the self keyword and print the values of student name and roll number using the self keyword and (.) operator

  • Create an object of the Student class. Then it will call the __init__ method by default (Here it initializes and prints the values inside constructor).

Example

# creating a class with the name Student class Student(object): # constructor of the student class def __init__(self): # initiaizing the values of attributes with None self.studentName = None self.rollNumber = None print('The Value of Student Name:',self.studentName) print('The Value of Roll Number:',self.rollNumber) #Creating the Object for the student class studentObject=Student()

Output

The Value of Student Name: None
The Value of Roll Number: None

In addition, it is good Python practice to derive all classes from "object" so that you can utilize new-style classes and name instance variables with the lowercase_with_underscore or initialLowerWithCaps convention. Class names are almost always written in the InitialCaps format.

Method 4: Using @dataclass decorator

This function is a decorator for adding generated special methods to classes

The dataclass module is introduced in Python 3.7 as a utility tool for creating structured classes designed specifically for data storage. These classes have particular attributes and functions that deal with data and its representation.

Example

# importing dataclasses from dataclasses import dataclass @dataclass class Student: StudentName: str rollNumber: str

Here we created two class attributes with the type of string. By default, the values of the student name and roll number will be None.

Conclusion

We learned how to declare class attributes with None values using several methods in this article. We also learned about the __init__() function and the self keyword in object-oriented programming.

Updated on: 22-Sep-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements