Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – more about class and instance attributes


Enter the following code into a text file, or an input cell in a worksheet:

class Test2():
    value1 = 5
        
    def method1(self):
        return 'Old Method '

instance_1 = Test2()
instance_2 = Test2()

print("Instance 1, value1 = " + str(instance_1.value1))
print("Instance 2, value1 = " + str(instance_2.value1))

print("Changing value1:")
instance_1.value1 = 6
print("Instance 1, value1 = " + str(instance_1.value1))
print("Instance 2, value1 = " + str(instance_2.value1))

print("Instance 1, method1: " + instance_1.method1())
print("Instance 2, method1: " + instance_2.method1())

def new_method():
    return 'New Method'

print("Adding a new method:") 
instance_1.method1 = new_method

print("Instance 1, method1: " + instance_1.method1())
print("Instance 2, method1: " + instance_2.method1())

The output should look like this:

sage: load("4460_9_7.py")
Instance 1, value1 = 5
Instance 2, value1 = 5
Changing value1:
Instance 1, value1...