Accessing attributes, Editing class attributes

 Accessing attributes, Editing class attributes

In Python, you can access and edit class attributes using the dot notation. Class attributes are shared among all instances of a class. Here's an example:


```python

class Car:

    # Class attribute

    wheels = 4


    def __init__(self, brand, model):

        # Instance attributes

        self.brand = brand

        self.model = model


# Creating objects

car1 = Car("Toyota", "Camry")

car2 = Car("Honda", "Accord")


# Accessing class attribute

print(car1.wheels)  # Output: 4

print(car2.wheels)  # Output: 4


# Accessing instance attributes

print(car1.brand)   # Output: Toyota

print(car2.model)   # Output: Accord


# Editing class attribute (affects all instances)

Car.wheels = 6


# Accessing updated class attribute

print(car1.wheels)  # Output: 6

print(car2.wheels)  # Output: 6


# Editing instance attribute (specific to the instance)

car1.brand = "Ford"


# Accessing updated instance attribute

print(car1.brand)   # Output: Ford

print(car2.brand)   # Output: Toyota (unchanged for car2)

```


In this example:


- `wheels` is a class attribute shared among all instances of the `Car` class.


- `brand` and `model` are instance attributes specific to each instance of the class.


- Class attributes are accessed and modified using the class name (`Car.wheels`), affecting all instances.


- Instance attributes are accessed and modified using the object name (`car1.brand`), affecting only that specific instance.


It's important to note that if you modify a class attribute, the change will be reflected in all instances of the class. If you modify an instance attribute, it only affects that particular instance.


### Class Methods for Attribute Modification:


You can also use class methods to modify class attributes in a controlled manner. Here's an example:


```python

class Car:

    wheels = 4


    def __init__(self, brand, model):

        self.brand = brand

        self.model = model


    @classmethod

    def upgrade_wheels(cls, new_wheels):

        cls.wheels = new_wheels


# Creating objects

car1 = Car("Toyota", "Camry")

car2 = Car("Honda", "Accord")


# Accessing class attribute

print(car1.wheels)  # Output: 4

print(car2.wheels)  # Output: 4


# Using class method to upgrade wheels

Car.upgrade_wheels(6)


# Accessing updated class attribute

print(car1.wheels)  # Output: 6

print(car2.wheels)  # Output: 6

```


In this example, the `upgrade_wheels` class method is used to modify the `wheels` class attribute. Class methods are bound to the class rather than an instance and can be used to modify class attributes in a more controlled manner.


Comments

Popular posts from this blog

Programming in Python