0

I want to run a static/class function from a python class' "initialization block" (and not from the __init__ constructor).

from . import config as cfg

class MyHandler():
    key_vault_client = SecretClient(cfg.kv_conf)
    credential, storage_client = MyHandler.initialize_storage_client()
    
    @classmethod
    def initialize_storage_client(cls):
        # check some constraints
        credential = ClientSecretCredential(
            client_id = cfg.client_id,
            client_secret = cls.get_secret(cfg.storage_client_secret),
            tenant_id = cfg.tenant_id
        )
        storage_client = StorageManagementClient(credential, cfg.subscription_id)
        return credential, storage_client 

    @classmethod
    def get_secret(cls, secret_name):
        return cls.key_vault_client.get_secret(secret_name).value

But I've realized that I can't call a static/class or any method (which would give my credential and storage_client variables the values in the above case) from a block which is the static initialization block in Java. Notice that the initialize_storage_client() calls the get_secret() method for secrets.

If I can do something like this:

class MagicalHandler():
    
    def __init__(self):
        self.object_prop_1 = "object_prop_1_value"
        self.object_prop_2 = self.get_object_prop_value()
    
    def get_object_prop_value(self):
        return "object_prop_2_value"
    
x = MagicalHandler()
print(x.object_prop_1)
print(x.object_prop_2)

Then why I can't do something like this:

class MagicalHandler():
    
    @classmethod
    def get_class_prop_value(cls):
        return "object_prop_2_value"
    
    class_prop_1 = "class_prop_1_value"
    class_prop_2 = MagicalHandler.get_class_prop_value()

print(MagicalHandler.class_prop_1)
print(MagicalHandler.class_prop_2)

or this:

class MagicalHandler():
    
    @staticmethod
    def get_class_prop_value():
        return "object_prop_2_value"
    
    class_prop_1 = "class_prop_1_value"
    class_prop_2 = MagicalHandler.get_class_prop_value()

print(MagicalHandler.class_prop_1)
print(MagicalHandler.class_prop_2)

What is the solution for the above problem?

elaspog
  • 1,635
  • 3
  • 21
  • 51
  • https://stackoverflow.com/questions/12718187/calling-class-staticmethod-within-the-class-body/12718272 – Danoram Dec 11 '20 at 12:00
  • Does this answer your question? [Calling class staticmethod within the class body?](https://stackoverflow.com/questions/12718187/calling-class-staticmethod-within-the-class-body) – Danoram Dec 11 '20 at 12:00

0 Answers0