Python Constructors for Imperial Artifacts

PythonPythonBeginner
Practice Now

Introduction

In the heart of the Ming dynasty's majestic palaces, a diligent eunuch embarks on a critical mission to document and manage the vast inventory of imperial treasures. Amidst the grandeur of ancient halls and opulent chambers, our protagonist, holding the title of "Keeper of Artifacts", must apply the utmost precision and care. Using the powerful and versatile tool of the Python language, he must maintain a meticulous record.

Your goal is to assist our faithful eunuch in mastering the concept of constructors in Python - essential for encapsulating the properties of every unique artifact and automating the process with class-based structures. In this immersive scenario, you'll learn how to define and utilize constructors, enhancing your skills to handle data with elegant efficiency – an endeavor worthy of the imperial court's reputation!


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") subgraph Lab Skills python/constructor -.-> lab-271534{{"`Python Constructors for Imperial Artifacts`"}} end

Python Class with Constructor

In this step, you will create a Python class that represents an artifact in the palace's collection. You will define a constructor to initialize its attributes such as name, age, and origin.

Please open a Python file named artifact.py in the ~/project directory with the following content:

class Artifact:
    def __init__(self, name, age, origin):
        self.name = name
        self.age = age
        self.origin = origin

## Example usage
if __name__ == "__main__":
    jade_vase = Artifact("Jade Vase", 150, "China")
    print(f"Artifact: {jade_vase.name}, Age: {jade_vase.age}, Origin: {jade_vase.origin}")

The Artifact class has an __init__ method which is a constructor in Python. It automatically gets called when you create a new instance of the class. The self parameter refers to the current instance of the class and is used to access variables that belong to the class.

Run the Python script by executing the following command in the terminal:

python ~/project/artifact.py

You should see the output:

Artifact: Jade Vase, Age: 150, Origin: China

Adding Methods to Artifact

Now, let's enhance the Artifact class by adding methods that allow the eunuch to display and update the artifact's information. You'll create a method to print the details of the artifact and another one to update its age.

Amend the artifact.py file to include the new methods:

class Artifact:
    def __init__(self, name, age, origin):
        self.name = name
        self.age = age
        self.origin = origin

    def display_info(self):
        print(f"Artifact: {self.name}, Age: {self.age}, Origin: {self.origin}")

    def update_age(self, new_age):
        if new_age >= 0:
            self.age = new_age
        else:
            print("Invalid age. Please enter a positive number.")

## Example usage
if __name__ == "__main__":
    jade_vase = Artifact("Jade Vase", 150, "China")
    jade_vase.display_info()
    jade_vase.update_age(160)
    jade_vase.display_info()

The display_info method prints out the details of an artifact. The update_age method allows updating the age attribute, ensuring that only valid, positive numbers are set.

Run the updated Python script by executing the corresponding command in the terminal again and observe the output.

The information below should be displayed on your terminal:

Artifact: Jade Vase, Age: 150, Origin: China
Artifact: Jade Vase, Age: 160, Origin: China

Summary

In this lab, you had an interactive walk through the ancient Ming dynasty palaces, where you assisted our character in documenting artifacts using Python constructors. The main focus was on understanding the concept of constructors in Python and how to manipulate class attributes through methods.

From creating a class and its constructor to adding functional methods, you gained practical experience. You learned how to instantiate objects, initialize their attributes, and manipulate object data with class-defined methods - a foundational skill set for any Python developer.

We hope you have grasped the basic idea of Python constructors and how they can be powerful tools for data encapsulation and object-oriented programming. Now, you can move forth and tackle even more complex programming challenges with the confidence of an imperial court's Keeper of Artifacts!

Other Python Tutorials you may like