【问题标题】:Python built-in functions for class object?类对象的Python内置函数?
【发布时间】:2019-11-04 06:27:57
【问题描述】:

我是 python 新手。我听说在 python 中,无论是类还是函数,一切都是对象。

据我所知,类对象是在程序启动时创建的。所以我想知道是否有一些用于初始化类变量或做某事的函数。

init 函数不能这样做,因为它的参数是 self ,它是类的一个实例。我想访问类本身。

class Example():

    def __init__(self):
# I know that this function is called when an instance of this class is created
        pass


    def __something__(cls):
# Is there some function for initializing class object?
# What I wanna do is I want to initialize class variables or call some functions...
# But __init__ function can't do because its parameter is self.
        pass

【问题讨论】:

  • 只需在class 定义中执行cls_attr = 'Foo'...!?
  • 是的,您正在寻找metaclass

标签: python python-3.x python-2.7


【解决方案1】:

在 Python 中,类对象是在运行时创建的,因为 Python 是 Dynamic Language

所以如果你想启动类变量,你可以在类定义之后立即设置它们

class Cls:
  cls_var = "before"

print(Cls.cls_var)
Cls.cls_var = "after"
print(Cls.cls_var)

这将打印“之前”和“之后”

【讨论】:

    【解决方案2】:

    你可以直接操作你定义的类。

    比如你的类名是Example,可以使用buildin method dir查看类方法(dir(Example)),使用type查看类类型(type(Example)),__dict__查看类属性( Example.__dict__) ...

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多