Is it possible to append a list declared static in python class?

Viewed 95

I have the following python code:

class university: 
    q_university = []
    
    def __init__(self, name, ranking, country):
        self.name = name
        self.ranking = ranking
        self.country = country 

    @staticmethod
    def create_object(name, ranking, country):
        university_object = university(name,ranking,country)
        q_university.append(university_object)
        return university_object

I would like to create the q_university declared static, so I can append the university object to it. However, when I declare it outside the function I am not able to access it within the function.

Any suggestions?

2 Answers

The q_university variable is a static or a class variable. So, rather than belonging to any particular object, it belongs to the class. Hence, to access it inside the method, you have to use the class name as follows: university.q_university.

class university: 
    q_university = []
    
    def __init__(self, name, ranking, country):
        self.name = name
        self.ranking = ranking
        self.country = country 

    @staticmethod
    def create_object(name, ranking, country):
        university_object = university(name,ranking,country)
        university.q_university.append(university_object)
        return university_object

obj = university.create_object("test",1,"count")
obj2 = university.create_object("test2",1,"count2")

#output - test2
print(obj2.name)

#output - 2
print(len(university.q_university))

This is similar to how you access a static method. You must be accessing your static method using university.create_object(...).

Use classmethod.

class university: 
    q_university = []
    
    def __init__(self, name, ranking, country):
        self.name = name
        self.ranking = ranking
        self.country = country 

    @classmethod
    def create_object(cls, name, ranking, country):
        university_object = cls(name,ranking,country)
        cls.q_university.append(university_object)
        return university_object
Related