如何在Python模块中禁用dir()?

huangapple go评论59阅读模式
英文:

How to disable dir() in python modules?

问题

I understand your request. Here's the translated portion:

"我知道在Python中,dir() 返回所有Python模块或共享对象上的属性和方法。

出于安全原因,我们公司需要在某些特定模块或共享对象上禁用 dir()

有人可以帮助我禁用它吗?

示例:

class Person:  
  name = "John"
  age = 36
  country = "Norway"

print(dir(Person))

输出:

['__class__', '__delattr__', ... 'age', 'country', 'name']

我需要的输出:

['__class__', '__delattr__', ...]"

英文:

I know dir() in python returns all the properties and methods on the python modules or shared objects.

For security reason our company needs to disable dir() on some specific modules or shared objects.

Can some one help me to disable it ?

Eg:

class Person:  
  name = "John"
  age = 36
  country = "Norway"

print(dir(Person))

Output:

['class', 'delattr', ... 'age', 'country', 'name']

I need the output:

['class', 'delattr', ...]

答案1

得分: -1

你可以像这样覆盖你的类中的 dir 函数:

class Person:  
  name = "John"
  age = 36
  country = "Norway"

  def __dir__(self):
    return ['class', 'delattr', 'doc', 'getattribute', 'setattr', 'subclasshook']

希望对你有所帮助!

英文:

You could just override the dir function in your class like this:

class Person:  
  name = "John"
  age = 36
  country = "Norway"

  def __dir__(self):
    return ['class', 'delattr', 'doc', 'getattribute', 'setattr', 'subclasshook']

Hope this helps!

huangapple
  • 本文由 发表于 2023年5月7日 03:44:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定