Python - Write program to Create a Class


Let's define a class named MyClass.

It should have a field named data.

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


class MyClass:               # Define a class object 
    def setdata(self, value):   # Define class's methods = value       # self is the instance 
    def display(self): 
        print(        # per instance 
# from   w ww.j av
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()                     # differs in each instance 
y.display()                     # Runs: MyClass.display(y)


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

You can assign to an explicit instance object: = "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