Class Methods

Use @classmethod to create alternative constructors.

IntermediateTopic: Object-Oriented Programs
Back

Python Class Methods Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to demonstrate class methods

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    @classmethod
    def from_string(cls, data):
        name, salary = data.split("-")
        return cls(name, float(salary))


e = Employee.from_string("Alice-75000")
print(e.name, e.salary)
Output
Alice 75000.0

Understanding Class Methods

The class method 'from_string' constructs Employee objects from a string representation.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents