Access a static method from a static variable

There are many answers to the question of how to access static variables from static methods (for example, this one and that one and excellent information on the topic here ), however, I am having problems in a different direction: how can you use static methods to initialize static variables. For instance:.

import os, platform
class A(object):
    @staticmethod
    def getRoot():
        return 'C:\\' if platform.system() == 'Windows' else '/'
    pth = os.path.join(A.getRoot(), 'some', 'path')

The last line gives the exception NameError: name 'A' is not defined. The same error occurs if I use @classmethodinstead @staticmethod.

Is it possible to access a static method from a class variable?

+4
source share
3 answers

, "" vatiable pth, . ?

import os, platform
class A(object):
    @staticmethod
    def getRoot():
        return 'C:\\' if platform.system() == 'Windows' else '/'
A.pth = os.path.join(A.getRoot(), 'some', 'path')

:

import os, platform
class A(object):
    @staticmethod
    def getRoot():
        return 'C:\\' if platform.system() == 'Windows' else '/'
    pth = os.path.join(getRoot.__func__(), 'some', 'path')

... ( @staticmethod, ).

- ( , ):

import os, platform
class A(object):
    _root = 'C:\\' if platform.system() == 'Windows' else '/'
    @staticmethod
    def getRoot():
        return A._root
    pth = os.path.join(_root, 'some', 'path')

... , , ?:) - , , .

+4

pth classproperty:

class A(object):
    @staticmethod
    def getRoot():
        return 'C:\\' if platform.system() == 'Windows' else '/'
    @classproperty
    def pth(cls):
        return os.path.join(cls.getRoot(), 'some', 'path')

classproperty , .

, IMHO, classmethod staticmethod.

+1

In the end, I made an Aextension to another class Bthat has the static method that I wanted. I.e:.

import os
import platform

class B(object):
    @staticmethod
    def getRoot():
        return r'C:\\' if platform.system() == 'Windows' else '/'

class A(B):
    pth = os.path.join(B.getRoot(), 'some', 'path')

Although this is what worked best for me, it is more a job than an answer.

-1
source

All Articles