简体   繁体   中英

Python: How to define a class attribute's value dynamically?

I need to set a class attribute dynamically at run time. How can this be achieved? There is no way that I have found to set a class attribute outside of the instance init which means that it runs each time a an instance is created. This only needs to happen one time (when the class definition is loaded).

REVISED EXAMPLE.

Ideally i need to do something like this, but it seems this is not possible:

# Note modules are python modules which extend the functionality of my reusable app. 
class Test():
    active_modules = Test.get_active_moduels()

    @classmethod
    def get_active_moduels(cls):
        #logic for collecting installed modules
        return installed

I could get the job done like this, but it seems silly and causes major problems. If i try to access active_modules before a Test class is instantiated i get [] even though there are active_modules.

# Note modules are python modules which extend the functionality of my reusable app. 
class Test():
    active_modules = []

    def __init__ (self):
        Test.get_active_moduels()

    @classmethod
    def get_active_moduels(cls):
        if not cls.active_modules:
            #logic for collecting installed modules
            .....
            cls.active_modules = installed_modules
        else:
            return cls.active_modules

I could get this done by creating another registry of active_modules , but I would think there is a way to accomplish this within the class...

It would be much easier to help if you used concrete terminology. What is a "sub"? In any case, your code can be simplified to:

def compute_defaults():
    they = []
    they.append('default_1')
    they.append('default_2')
    return they

class Test():
    active_subs = compute_defaults()

    def __init__(self, sub=None):
        if sub:
            self.active_subs.append(sub)

Then you can use your code as you wish:

t1 = Test()
#active will have the installed subs.
active = t1.active_subs

Don't over-complicate your code with getters and setters needlessly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM