Jump to content

Python - Accessing class attributes, decorators

Go to solution Solved by fizzlesticks,

You'd use Class.Attribute instead of Object.Attribute. So Sorts.swaps.

I am working on an assignment for a course that I am taking, so I cannot change the underlying methodology of how the program will work. Anyways, I have a Sorts class, which contains multiple methods which are different types of sorting algorithms. Each method is preceded by the @staticmethod decorator. At the beginning of the class is a global variable, which each of the methods updates. The outline of the code is as follows:

 

 

Class Sorts:

        swaps = 0

 

       @staticmethod

       def bubble_sort(array):

        ....

 

 

In another python module, I have a function which will take in a function name as a parameter (that being one of the sort algorithms name), and will sort an unsorted array using that method. Then, I need to be able to grab the swaps value. Since decorators are used, we run a sorting algorithm by the following

 

 

from sort_methods import Sorts

sort_func = Sort.bubble_sort

 

#This will apply the sorting method to an unsorted array. In the bubble sort method in the Sorts class, it updates the swaps value, counting every time a swap is done

sort_func(input_array)

 

I am wondering how I can then access the swaps value? Normally, you would create an object, and then access the value by Object.Attribute = whatever. However, since we are using the @staticmethod decorator, we do not need to explicitly create an object. So how can I reference the attribute when we do not have an explicit object to refer to?

 

 

Thanks!

Link to comment
https://linustechtips.com/topic/406820-python-accessing-class-attributes-decorators/
Share on other sites

Link to post
Share on other sites

Brilliant, that works perfectly. Thanks again!!

 

You can also do:

from sort_methods.Sorts import bubble_sort

Which will give you the function bubble_sort in the current scope (ie, you can just call it as bubble_sort(stuff) )

 

I take it all back. I'm way too tired to be writing code apparently.

--Neil Hanlon

Operations Engineer

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×