class
Python Class
In Python, a class is a template for creating objects. It defines the attributes (properties) and behaviors (methods) that an object of the class should have.
Here is an example of a simple class in Python:
class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print("Woof!") # Create an object of the Dog class dog1 = Dog("Fido", 3) # Access the attributes of the object print(dog1.name) # Output: "Fido" print(dog1.age) # Output: 3 # Call the bark method of the object dog1.bark() # Output: "Woof!"
The __init__ method is a special method in Python classes that is used to initialize the attributes of an object when it is created. It is called the "constructor" method.
In the example above, the Dog class has two attributes: name and age. It also has a method called bark, which just prints a string to the console.
To create an object of the Dog class, we use the syntax dog1 = Dog("Fido", 3). This creates an object with the name "Fido" and age 3. We can then access the attributes of the object using dot notation (e.g. dog1.name) and call its methods using the same notation (e.g. dog1.bark()).
No comments