python中的类中是否有静态块
我对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要做到这一点,只需将代码直接放在类定义下(与类的函数定义并行)。
直接在类中的所有代码都会在类的命名空间中创建该类型时执行。示例:
只需填写最后一位为您提供的信息:您的方法函数
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:
Just to fill out the last bit of information for you: your method function
def
s 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 adef
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.
有关 Python 中静态变量/函数的更多信息,请参阅此处:Python 中的静态类变量
See here for more information about static variables/functions in Python: Static class variables in Python