python中的类中是否有静态块

发布于 2024-12-11 16:01:20 字数 358 浏览 0 评论 0原文

我对 python 比较陌生 我只想为一个类运行一次代码块。就像java中的static块一样。

例如:

class ABC:
    execute this once for a class.

python 中有这样的选项吗?

在java中我们这样写。对于一个类,这仅在加载类时执行一次。不适用于每个对象创建

public class StaticExample{
    static {
        System.out.println("This is first static block");
    }
}

谢谢

I am relatively new to python
I would like to run a block of code only once for a class. Like the static block in java.

for eg:

class ABC:
    execute this once for a class.

Is there any such options available in python?

In java we write it like this. This is executed only once for a class, at the time the class is loaded. Not for every object creation

public class StaticExample{
    static {
        System.out.println("This is first static block");
    }
}

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

星光不落少年眉 2024-12-18 16:01:20

要做到这一点,只需将代码直接放在类定义下(与类的函数定义并行)。

直接在类中的所有代码都会在类的命名空间中创建该类型时执行。示例:

class Test:
    i = 3
    y = 3 * i
    def testF(self):
        print Test.y

v = Test()
v.testF()
# >> 9

只需填写最后一位为您提供的信息:您的方法函数 def 也正在执行(就像您在全局命名空间上定义函数时它们被“执行”一样),但它们不会被调用。执行 def 显然没有 Python 的面向

对象特性非常聪明,但需要花一些时间来理解它,坚持下去,它是一种非常有趣的语言。

To do this just put the code directly under the class definition (parallel to the function definitions for the class.

All code directly in the class gets executed upon creation of that type in the class' namespace. Example:

class Test:
    i = 3
    y = 3 * i
    def testF(self):
        print Test.y

v = Test()
v.testF()
# >> 9

Just to fill out the last bit of information for you: your method function defs are also being executed (just like they get "executed" when you define a function on the global namespace), but they aren't called. It just happens to be that executing a def has no obviously visible results.

Python's object-oriented-ness is quite clever, but it takes a bit to get your head around it! Keep it up, it's a very fun language.

格子衫的從容 2024-12-18 16:01:20
>>> class MyClass():
...     print "static block was executed"
... 
static block was executed
>>> obj = MyClass()
>>>

有关 Python 中静态变量/函数的更多信息,请参阅此处:Python 中的静态类变量

>>> class MyClass():
...     print "static block was executed"
... 
static block was executed
>>> obj = MyClass()
>>>

See here for more information about static variables/functions in Python: Static class variables in Python

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文