别名是一个完全静态类的引用

时间:2016-03-08 12:02:13

标签: python reference static-methods

让我们以下面的代码为例。

public class JarLoader extends URLClassLoader {

public JarLoader() {
    super(new URL[0], ClassLoader.getSystemClassLoader());
}

private static final String ENDING_CLASS = ".class", URL_PREFIX = "file:";

public final Set<Class<?>> loadCraftbukkit(final JarFile pJar) {
    if (pJar != null) {

        try {
            addURL(new URL(URL_PREFIX + pJar.getName()));
            final Enumeration<JarEntry> entries = pJar.entries();
            final Set<Class<?>> loadedClasses = new HashSet<>();
            while (entries.hasMoreElements()) {
                final JarEntry entry = entries.nextElement();
                final String className = getClassName(entry);
                if (className != null) {
                    try {
                        final Class<?> loadedClass = loadClass(className);
                        loadedClasses.add(loadedClass);
                    } catch (ClassNotFoundException | NoClassDefFoundError pExc) {
                        // ignore invalid class
                    }
                }
            }
            return loadedClasses;
        } catch (MalformedURLException | ClassFormatError ignore) {
            // won't happen if legal jarfile
        }
    }
    return null;
}

private final String getClassName(final JarEntry pEntry) {
    final String name = pEntry.getName();
    if (name.endsWith(ENDING_CLASS)) {
        return name.substring(0, name.lastIndexOf(ENDING_CLASS)).replace('/', '.');
    }
    return null;
}
}

有什么方法可以缩短同一班级内对class StaticUtilities: @staticmethod def methodA(): return 1 @staticmethod def methodB(): a = StaticUtilities.methodA() return a + 1 的号召?

如果我从另一个班级访问这个,我可以使用

methodA

1 个答案:

答案 0 :(得分:1)

如果methodB需要访问类中的其他属性(即使它们是静态方法),它不是真正的静态。您可以轻松地将其设为类方法,而不是:

class StaticUtilities:

    @staticmethod
    def methodA():
        return 1

    @classmethod
    def methodB(cls):
        return cls.methodA() + 1

使用中:

>>> StaticUtilities.methodB()
2