Python - Write program to Create a Class

Requirements

Let's define a class named MyClass.

It should have a field named data.

Add a method to MyClass to display data's value.

Demo

class MyClass:               # Define a class object 
    def setdata(self, value):   # Define class's methods 
        self.data = value       # self is the instance 
    def display(self): 
        print(self.data)        # self.data: per instance 
# from   w  w w  .  j a  va  2 s.  co m
x = MyClass()                # Make two instances 
y = MyClass()                # Each is a new namespace 
x.setdata("King Arthur")        # Call methods: self is x 
y.setdata(3.14159)              # Runs: MyClass.setdata(y, 3.14159) 
x.display()                     # self.data differs in each instance 
y.display()                     # Runs: MyClass.display(y)

Result

We can change instance attributes in the class itself by assigning to self in methods.

You can assign to an explicit instance object:

x.data = "New value"            # Can get/set attributes 
x.display()                     # Outside the class too 

We could even generate an new attribute in the instance's namespace by assigning to its name outside the class's method functions:

x.anothername = "test"          # Can set new attributes here too! 

This would attach a new attribute called anothername to the instance object x.

Related Topic