Python Slots Class Attribute
- Related Questions & Answers
- Selected Reading
A property is created by assigning the result of a built-in function to a class attribute: attribute = property (fget, fset, fdel, doc) The property attribute take four optional positional. The slots declaration in this class creates a class attribute called 'slots', the class dictionary is unaffected. The KeyedRef2 class is a new-style class so the slots declaration causes special compact attributes to be created for each name in the slots list and saves space by not creating attribute dictionaries.
As an object oriented programming language python stresses on objects. Classes are the blueprint from which the objects are created. Each class in python can have many attributes including a function as an attribute.
Accessing the attributes of a class
To check the attributes of a class and also to manipulate those attributes, we use many python in-built methods as shown below.
getattr() − A python method used to access the attribute of a class.
hasattr() − A python method used to verify the presence of an attribute in a class.
setattr() − A python method used to set an additional attribute in a class.
The below program illustrates the use of the above methods to access class attributes in python.
Example
Output
Running the above code gives us the following result −
Accessing the method of a class
To access the method of a class, we need to instantiate a class into an object. Then we can access the method as an instance method of the class as shown in the program below. Here through the self parameter, instance methods can access attributes and other methods on the same object.
Example
Python Check Class Attribute
Output
Running the above code gives us the following result −
Accessing the method of one class from another
Python Set Class Attribute
To access the method of one class from another class, we need to pass an instance of the called class to the calling class. The below example shows how it is done.
Example
Python Get All Class Attributes
Output
Running the above code gives us the following result −