Logo

Developer learning path

Python

Attributes and Methods in Python

Attributes and Methods

71

#description

In Python, an object is an instance of a class, which has attributes and methods.

Attributes are data variables that hold values that describe the state of an object, such as its name, age, or size. These values can be accessed and manipulated by the object's methods.

Methods, on the other hand, are functions that operate on object data and can perform various actions, such as updating the object's attributes, or returning new values based on the object's state.

For example, let's say we have a class called "Person" with attributes such as "name", "age", and "gender". We can define methods like "speak" and "walk" to describe actions that a Person can perform.

Here's an example:

                    
class Person:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
    
    def speak(self, message):
        print(self.name + " says: " + message)
    
    def walk(self):
        print(self.name + " is walking.")

# create an instance of the Person class
john = Person("John", 25, "Male")

# access and update attributes
print(john.name) # "John"
john.age = 26

# call methods
john.speak("Hello, world!") # "John says: Hello, world!"
john.walk() # "John is walking."
                  

In this example, we create a Person object with the name "John", age 25, and gender "Male". We can access and update its attributes using dot notation, and call its methods by invoking them with parentheses.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.