Defining Specific Data Types with Python

Defining Specific Data Types

In Python, you can define and work with specific data types beyond the built-in types. This includes creating custom data types using classes and utilizing more advanced data structures. Here, we’ll cover defining custom data types, using type hints, and working with complex data structures.

Defining Custom Data Types

Custom data types can be defined using classes. Classes allow you to create objects with specific attributes and methods, giving you control over the data and behavior of those objects.

Creating a Class:

To define a custom data type, you use a class. A class can contain attributes (data) and methods (functions) that operate on that data.

Example: 

class Person:
   def __init__(self, name: str, age: int):
        self.name = name
        self.age = age
    def greet(self) -> str:
        return f"Hello, my name is {self.name} and I am {self.age} years old."
    def have_birthday(self):
        self.age += 1
# Creating an instance of the Person class
person1 = Person("Alice", 30)
print(person1.greet())  # Output: Hello, my name is Alice and I am 30 years old.
person1.have_birthday()
print(person1.greet())  # Output: Hello, my name is Alice and I am 31 years old.

 Class Components:

  • __init__ Method: This is the constructor method that initializes the object’s attributes.
  • Attributes: Variables that belong to the object.
  • Methods: Functions defined inside the class that operate on the object’s data.

Using Type Hints for Custom Types

Python’s type hints allow you to specify what types are expected for class attributes and methods. This improves code clarity and can be used with type checkers like mypy.

Example with Type Hints: 

from typing import List
class Course:
    def __init__(self, title: str, students: List[str]):
        self.title = title
        self.students = students
    def add_student(self, student: str):
        self.students.append(student)
    def get_student_count(self) -> int:
        return len(self.students)
# Creating an instance of the Course class
course = Course("Python Programming", ["Alice", "Bob"])
course.add_student("Charlie")
print(course.get_student_count())  # Output: 3

 Working with Advanced Data Structures

Python offers several advanced data structures beyond the basic built-in types. These include:

  • Named Tuples: Use the collections.namedtuple function to create tuple subclasses with named fields.

Example: 

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y)  # Output: 10 20
Dataclasses: Introduced in Python 3.7, dataclasses simplify class definitions by automatically adding special methods like __init__() and __repr__().

 Example: 

From dataclasses import dataclass
@dataclass
class Book:
    title: str
    author: str
    year: int
book = Book("1984", "George Orwell", 1949)
print(book)  # Output: Book(title='1984', author='George Orwell', year=1949)

Enums: The enum module allows you to define enumerations, a set of symbolic names bound to unique,

constant values.

Example: 

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
print(Color.RED)        # Output: Color.RED
print(Color.RED.name)   # Output: RED
print(Color.RED.value)  # Output: 1

 Type Aliases

Type aliases provide a way to create alternative names for existing types, which can help improve code readability and maintainability.

Example: 

from typing import List, Tuple
# Define a type alias
Coordinates = List[Tuple[int, int]]
def get_center(points: Coordinates) -> Tuple[int, int]:
    x_coords, y_coords = zip(*points)
    return (sum(x_coords) // len(points), sum(y_coords) // len(points))
# Using the type alias
points = [(1, 2), (3, 4), (5, 6)]
center = get_center(points)
print(center)  # Output: (3, 4)

Practical Examples of Custom Types

Example 1: Banking Application

Create a class to model a bank account with methods for depositing and withdrawing funds.

from typing import List, Tuple
# Define a type alias
Coordinates = List[Tuple[int, int]]
def get_center(points: Coordinates) -> Tuple[int, int]:
    x_coords, y_coords = zip(*points)
    return (sum(x_coords) // len(points), sum(y_coords) // len(points))
# Using the type alias
points = [(1, 2), (3, 4), (5, 6)]
center = get_center(points)
print(center)  # Output: (3, 4)

Example 2: Student Grades

Define a class to handle student grades with methods to add grades and calculate the average. 

class StudentGrades:
    def __init__(self, student_name: str):
        self.student_name = student_name
        self.grades = []
    def add_grade(self, grade: float):
        if 0 <= grade <= 100:
            self.grades.append(grade)
        else:
            print("Grade must be between 0 and 100.")
# Creating and using a student grades record
student = StudentGrades("Alice")
student.add_grade(90)
student.add_grade(85)
print(student.average_grade())  # Output: 87.5

 Summary

  • Custom Data Types: Use classes to create custom data types with specific attributes and methods.
  • Type Hints: Provide hints about expected types in classes and functions to improve code clarity.
  • Advanced Data Structures: Utilize named tuples, data classes, and enumerations for more complex data handling.
  • Type Aliases: Create alternative names for existing types to enhance readability and maintainability.
  • Practical Examples: Apply custom types to model real-world entities and operations, such as banking accounts and student grades.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *