Python 中是否可以使用静态类变量?

编程入门 行业动态 更新时间:2024-10-26 12:27:48
本文介绍了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 中是否可以使用静态类变量?

本文发布于:2023-11-08 11:42:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569274.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   变量   静态   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!