Saturday, December 28, 2024
Google search engine
HomeLanguagesPython objects

Python objects

A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state.

Refer to the below article to know about the basics of Python classes.

Class objects

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. To understand objects let’s consider an example, let’s say there is a class named the dog that contains certain attributes like breed, age, color, and behaviors like barking, sleeping, and eating. An object of this class is like an actual dog, let’s say a dog of breed pug who’s seven years old. You can have many dogs to create many different instances, but without the class as a guide, you would be lost, not knowing what information is required. An object consists of:

  • State: It is represented by attributes of an object. It also reflects the properties of an object.
  • Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects.
  • Identity: It gives a unique name to an object and enables one object to interact with other objects.

python-objects

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances. python-objects Example: 

Python3




# Python program to demonstrate instantiating
# a class
class Dog:
 
    # A simple class attribute
    attr1 = "mamal"
    attr2 = "dog"
 
    # A sample method
    def fun(self):
        print("I'm a", self.attr1)
        print("I'm a", self.attr2)
         
    def greet(self):
      print("hope you are doing well")
 
 
# Driver code
# Object instantiation
Rodger = Dog()
 
# Accessing class attributes and method through objects
print(Rodger.attr1)
print(Rodger.attr2)
Rodger.fun()
Rodger.greet()


Output

mamal
dog
I'm a mamal
I'm a dog
hope you are doing well
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments