Python 中是否可以使用静态类变量? [英] Are static class variables possible in Python?

查看:42
本文介绍了Python 中是否可以使用静态类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中是否可以有静态类变量或方法?执行此操作需要什么语法?

解决方案

在类定义内声明但不在方法内的变量是类或静态变量:

<预><代码>>>>类我的类:...我 = 3...>>>我的课堂3

正如@millerdev 指出的那样,这创建了一个类-级别 i 变量,但这与任何实例级别的 i 变量不同,因此您可以拥有

<预><代码>>>>m = MyClass()>>>米 = 4>>>MyClass.i, m.i>>>(3, 4)

这与 C++ 和 Java 不同,但与 C# 没有太大不同,其中不能使用对实例的引用来访问静态成员.

请参阅 Python 教程对类和类对象.

@Steve Johnson 已经回答了关于静态方法,也记录在 Python 库参考中的内置函数"下.

C 类:@静态方法def f(arg1, arg2, ...): ...

@beidy 推荐 classmethods 而不是 staticmethod,作为方法然后接收类类型作为第一个参数,但我对这种方法相对于静态方法的优势仍然有些模糊.如果你也是,那可能没关系.

Is it possible to have static class variables or methods in Python? What syntax is required to do this?

解决方案

Variables declared inside the class definition, but not inside a method are class or static variables:

>>> class MyClass:
...     i = 3
...
>>> MyClass.i
3 

As @millerdev points out, this creates a class-level i variable, but this is distinct from any instance-level i variable, so you could have

>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)

This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.

See what the Python tutorial has to say on the subject of classes and class objects.

@Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument, but I'm still a little fuzzy on the advantages of this approach over staticmethod. If you are too, then it probably doesn't matter.

这篇关于Python 中是否可以使用静态类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆