How Do You Use a Class in Python to Test The __init__ Constructor’s Default Settings?

Problem scenario
You want to instantiate a class with default values if the class was called to create an object without all the settings. You want to verify you know how to code this basic object-oriented programming feature. You want to print out specific member variables of an object. How do you do this?

Solution
Use this program:

#!/bin/python3

class Computer(object):
    def __init__(self, cpu_cores = "1", ram = "1G"):
        self.cpu_cores = cpu_cores
        self.ram = ram
    pass


desktop = Computer("2", "2G")

laptop = Computer(1)

print(desktop.cpu_cores)
print(desktop.ram)
print("Desktop attributes above and laptop attributes below")
print(laptop.cpu_cores)
print(desktop.ram)

Leave a comment

Your email address will not be published. Required fields are marked *