Python · Chapter 28 of 45
Python Classes
A CLASS is a blueprint for objects. Define it with `class`, and give it methods (functions) and attributes (data).
`__init__` is the constructor — it runs when an object is created.
Syntax
class ClassName:
def __init__(self, params):
self.attr = value
def method(self):
...self
The first parameter of every instance method is `self`, which refers to the current object.
Attributes
Set inside `__init__` with `self.name = value`. Access on any instance with `obj.name`.
Example 1 (python)
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
d = Dog("Rex")
print(d.bark())Output
Rex says woof!Define a Dog class, create an instance, call a method.
Example 2 (python)
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return 3.14 * self.r ** 2
print(Circle(5).area())Output
78.5Create and use a Circle in one expression.
Key points
- `class Name:` defines a class.
- `__init__(self, ...)` is the constructor.
- `self` refers to the current object.
- Access members with `obj.name`.
💡 Note: Use CapitalizedNames for classes (PascalCase) and snake_case for functions and variables.
