Python 如何从单独的文件访问类中的封装值?
我正在开发一个包含多个文件的大型python程序,我遇到了一个问题。我从一个单独的文件在一个类中创建了5个实例,但我不确定创建后如何访问它。它也是封装的。我将展示一个非常简单的例子来说明我的问题是什么。本例将使用两个文件,文件1和文件2 文件1Python 如何从单独的文件访问类中的封装值?,python,file,class,python-3.x,encapsulation,Python,File,Class,Python 3.x,Encapsulation,我正在开发一个包含多个文件的大型python程序,我遇到了一个问题。我从一个单独的文件在一个类中创建了5个实例,但我不确定创建后如何访问它。它也是封装的。我将展示一个非常简单的例子来说明我的问题是什么。本例将使用两个文件,文件1和文件2 文件1 class Hello(): def set_num(self,one,two): self.__first = one self.__second = two 文件2 import file_1 def ge
class Hello():
def set_num(self,one,two):
self.__first = one
self.__second = two
文件2
import file_1
def get_it():
I = -1
first_one = 50
second_one = 75
for i in range(5):
I+=1
first_one = first_one*2
second_one = second_one*1.5
newI = "a"+str(I)
new = file_1.Hello()
file_1.Hello.set_num(new,first_one,second_one)
def get_first():
print(a1._Hello__first)
所以我只运行文件_2,get _it()。运行时,应创建以下内容(全部在幕后):
这就是数据应该存储的地方。我需要的是从文件2中访问数据,我将在文件2中创建另一个函数来访问它。
但我的问题是,我将如何访问它?
这是文件_2中的第二个函数,它应该返回100,但它给出了一个错误:
def get_first():
print(a1._Hello__first)
当我运行它时,我得到“AttributeError:'str'对象没有属性‘Hello_first’”。
因此,我的问题是,我如何访问这些数据?通常,在创建一个类的多个实例时,最好将它们放在您可以找到的位置,例如,在一个容器中,如
dict
或list
:
instances = [] # list to hold instances
for _ in range(5):
first_one *= 2
second_one *= 1.5
new = file_1.Hello() # create instance
new.set_num(first_one, second_one) # set number
instances.append(new) # add to list
现在,当您要打印它们时:
for instance in instances:
print(instance._Hello__first)
print(instance._Hello__second)
无法创建名为
“1”
的对象。只需创建一个列表并将对象附加到其中。您可以编写new.set\num(new,first\u one,second\u one)
,而不是file\u 1.Hello.set\u num(first\u one,second\u one)
——您可以通过实例调用方法,而不是手动调用类上的方法并将实例作为第一个参数传递。(我也不知道你在用I
做什么)@BrenBarn,这是一个学校项目,所以我别无选择,只能使用课堂。关于如何创建多个实例有什么想法吗?你可以使用一个类。你不能做的是创建一个名为“1”
@BrenBarn的类的实例,我改为a1,a2。。。但我还是犯了同样的错误,非常感谢!这正是我要找的!
for instance in instances:
print(instance._Hello__first)
print(instance._Hello__second)