【问题标题】:using an attribute from a class in python without creating an object在python中使用类中的属性而不创建对象
【发布时间】:2017-07-09 20:52:27
【问题描述】:

我想知道是否可以在不从该类创建对象的情况下使用另一个文件中的类的属性,例如,如果我在 File_A 中有 Class_A 并且我将 Class_A 导入 File_B 我是否必须使用 Class_A 作为File_B 中的对象以访问其属性?

【问题讨论】:

  • 类的全部意义在于充当创建对象的模板。如果您想要一个没有实例的实例属性,这听起来像是一个基本的设计问题。为什么这是一个属性,而不是模块级变量?
  • 我不确定你的意思,你能提供一些样本吗?

标签: python class import attributes


【解决方案1】:

最简单的方法:

In [12]: class MyClass(object):
...:         attr = 'attr value'

In [15]: MyClass.attr
Out[15]: 'attr value'

你也可以使用 __dict__ 属性:

__dict__ 是包含类名称空间的字典。

In [15]: MyClass.__dict__.get('attr', None)
Out[15]: 'attr value'

如果需要使用方法,请使用 staticmethod 装饰器:

In [12]: class MyClass(object):
...:         @staticmethod
...:         def the_static_method(x):
...:             print(x)


In [15]: MyClass.the_static_method(2)
Out[15]: 2

【讨论】:

  • 当您可以直接访问属性时为什么要使用__dict__MyClass.attr
  • 是的,你是对的,我们不需要字典。处理缺少的属性更方便。
  • 问题是每当我使用 class.name 时,它​​说该类没有属性名称,即使它确实如此,我已经检查了拼写。
  • 你看到了什么:print(class._dict_)?
  • '{'dict': dict' of 'armor1' objects>, 'module' : 'the_shop', 'weakref': weakref' of 'armor1' objects>, 'doc': None, 'init': init at 0x028C1130>}'
【解决方案2】:

确实没有理由在其他对象中创建一个新对象来利用另一个对象的属性和方法。

您只想在 File_B 中创建 Class_A 的实例以使用它的属性和方法。

例如:

import Class_A

#instance of Class_A
classA = Class_A('params')

#property1 is a property in classA
classA.property1

#doSomething is a method in classA
classA.doSomething()

在此处阅读有关 OOP 的更多信息 http://www.python-course.eu/object_oriented_programming.php

【讨论】:

  • classA = Class_A 不创建实例。我想你想真正调用类对象。
  • ClassA = Class_A 不适用于我的代码。我有两个很多类,并且在两个很多文件之间移动
猜你喜欢
  • 2018-08-07
  • 1970-01-01
  • 2017-08-11
  • 2020-09-23
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
相关资源
最近更新 更多