Skip to main content

Python Methods and attributes

In Python, methods and attributes are the two primary components of a class that help define the behavior and state of objects created from the class. Here's a detailed overview of each:

Attributes

Attributes are variables that belong to a class (class attributes) or to an instance of a class (instance attributes).

Class Attributes

Class attributes are shared across all instances of the class. They are defined within the class but outside any methods.

class MyClass: # Class attribute class_attr = "I am a class attribute" # Accessing class attribute print(MyClass.class_attr) # Output: I am a class attribute

Instance Attributes

Instance attributes are unique to each instance of the class. They are usually defined within the __init__ method.

class MyClass: def __init__(self, value): # Instance attribute self.instance_attr = value # Creating instances obj1 = MyClass(10) obj2 = MyClass(20) # Accessing instance attributes print(obj1.instance_attr) # Output: 10 print(obj2.instance_attr) # Output: 20


Methods

Methods are functions defined within a class that operate on instances of that class. There are several types of methods in Python.

Instance Methods

Instance methods operate on an instance of the class and can access and modify the instance attributes. The first parameter is always self, which refers to the instance calling the method.

class MyClass: def __init__(self, value): self.value = value def instance_method(self): return f"Instance method called. Value is {self.value}" # Creating an instance obj = MyClass(10) # Calling an instance method print(obj.instance_method()) # Output: Instance method called. Value is 10

Class Methods

Class methods operate on the class itself rather than on instances. They are defined with the @classmethod decorator, and the first parameter is cls, which refers to the class.

class MyClass: class_attr = "I am a class attribute" @classmethod def class_method(cls): return f"Class method called. Class attribute is {cls.class_attr}" # Calling a class method print(MyClass.class_method()) # Output: Class method called. Class attribute is I am a class attribute

Static Methods

Static methods do not operate on an instance or the class itself. They are defined with the @staticmethod decorator and do not take a self or cls parameter.

class MyClass: @staticmethod def static_method(): return "Static method called" # Calling a static method print(MyClass.static_method()) # Output: Static method called


Example of a Class with Attributes and Methods

Here’s a comprehensive example that demonstrates defining and using attributes and methods:

class Car: # Class attribute vehicle_type = "Car" def __init__(self, brand, model, year): # Instance attributes self.brand = brand self.model = model self.year = year # Instance method def description(self): return f"{self.year} {self.brand} {self.model}" # Class method @classmethod def is_motor_vehicle(cls): return cls.vehicle_type == "Car" # Static method @staticmethod def car_sound(): return "Vroom vroom" # Creating an instance of Car my_car = Car("Toyota", "Corolla", 2020) # Accessing class attribute print(Car.vehicle_type) # Output: Car # Accessing instance attributes print(my_car.brand) # Output: Toyota print(my_car.model) # Output: Corolla print(my_car.year) # Output: 2020 # Calling instance method print(my_car.description()) # Output: 2020 Toyota Corolla # Calling class method print(Car.is_motor_vehicle()) # Output: True # Calling static method print(Car.car_sound()) # Output: Vroom vroom


Summary

  • Attributes: Variables that belong to a class or instance.
    • Class Attributes: Shared among all instances.
    • Instance Attributes: Unique to each instance.
  • Methods: Functions defined within a class.
    • Instance Methods: Operate on an instance, first parameter is self.
    • Class Methods: Operate on the class, first parameter is cls.
    • Static Methods: Do not operate on the instance or class, no special first parameter.

Understanding methods and attributes is essential for effectively using classes and objects in Python, enabling you to create modular, reusable, and maintainable code.

Comments

Popular posts from this blog

Power BI tenant settings and admin portal

As of my last update, Power BI offers a dedicated admin portal for managing settings and configurations at the tenant level. Here's an overview of Power BI tenant settings and the admin portal: 1. Power BI Admin Portal: Access : The Power BI admin portal is accessible to users with admin privileges in the Power BI service. URL : You can access the admin portal at https://app.powerbi.com/admin-portal . 2. Tenant Settings: General Settings : Configure general settings such as tenant name, regional settings, and language settings. Tenant Administration : Manage user licenses, permissions, and access rights for Power BI within the organization. Usage Metrics : View usage metrics and reports to understand how Power BI is being used across the organization. Service Health : Monitor the health status of the Power BI service and receive notifications about service incidents and outages. Audit Logs : Access audit logs to track user activities, access requests, and administrative actions wit...

Using bookmarks and buttons for navigation

Using bookmarks and buttons for navigation in Power BI allows you to create interactive experiences within your reports, guiding users through different views and sections. Let's walk through how to use bookmarks and buttons for navigation: Step 1: Create Bookmarks Navigate to the "View" tab : Open your report in Power BI Desktop and navigate to the "View" tab. Create Bookmarks : Select the elements (visuals, slicers, shapes, etc.) that you want to bookmark. Click on the "Bookmark" button in the "View" tab or right-click and select "Add bookmark". Name your bookmark and ensure the "Data" and "Display" options are selected if you want to capture filter states and visual display states. Repeat for Additional Views : Create bookmarks for each view or section of your report that you want to navigate to. Step 2: Create Buttons Insert Buttons : Go to the "Home" tab and click on the "Buttons" dropdow...

Understanding the Power BI ecosystem and workflow

Understanding the Power BI ecosystem and workflow involves getting familiar with the various components of Power BI and how they interact to provide a comprehensive data analysis and visualization solution. Here's a detailed explanation: Power BI Ecosystem The Power BI ecosystem consists of several interconnected components that work together to enable users to connect to data sources, transform and model data, create visualizations, and share insights. The main components are: Power BI Desktop Power BI Service Power BI Mobile Power BI Gateway Power BI Report Server Power BI Embedded PowerBI Workflow Here’s a typical workflow in the Power BI ecosystem: Step 1: Connect to Data Sources Power BI Desktop:  Connect to various data sources like Excel, SQL databases, cloud services, and more. Power BI Gateway:  If using on-premises data sources, install and configure the gateway for secure data transfer. Step 2: Data Transformation and Modeling Power BI Desktop:  Use Power Query...