Python 3.x 如何使用导入将当前对象状态获取到python中的不同模块
我有两个类catalog类和library类我创建了catalog类的对象,并在catalog类方法中执行了一些操作,我想使用同一个对象和library类中执行的所有操作来执行进一步的操作,同时保持这些状态 我试过上面的方法,但没有成功 以上两个类都位于不同的模块或文件中。。。Python 3.x 如何使用导入将当前对象状态获取到python中的不同模块,python-3.x,oop,project,Python 3.x,Oop,Project,我有两个类catalog类和library类我创建了catalog类的对象,并在catalog类方法中执行了一些操作,我想使用同一个对象和library类中执行的所有操作来执行进一步的操作,同时保持这些状态 我试过上面的方法,但没有成功 以上两个类都位于不同的模块或文件中。。。 ... 请帮我解决这个问题,谢谢……我想你要找的是一种叫做继承的东西。 假设Catalog类位于名为Catalog.py的文件中,看起来像这样 class Catalog: def __init__(self):
... 请帮我解决这个问题,谢谢……我想你要找的是一种叫做继承的东西。 假设Catalog类位于名为Catalog.py的文件中,看起来像这样
class Catalog:
def __init__(self):
self.different_book_count = 0
self.books = []
def accessCurrentCatalog(self):
return self
class Library:
def __init__(self,name, location, age, aadhar_id,emp_id):
super().__init__(name, location, age, aadhar_id)
self.emp_id = emp_id
def __repr__(self):
return self.name + self.location + self.emp_id
def accesCurrentCatalog(self):
catalog = Catalog().accessCurrentCatalog
return catalog
def addBook(self,name,author,publish_date,pages):
catalog = self.accesCurrentCatalog()
catalog.addBook(name,author,publish_date,pages)
class Catalog:
def __init__(self, name, location, age, aadhar_id, emp_id):
self.different_book_count = 0
self.books = []
def accessCurrentCatalog(self):
# do stuff
pass
def addBook(self, name, author, publish_date, pages):
# do stuff
pass
您可以导入该类,并使用super()。\uuuu init\uuuu()
看起来像这样
class Catalog:
def __init__(self):
self.different_book_count = 0
self.books = []
def accessCurrentCatalog(self):
return self
class Library:
def __init__(self,name, location, age, aadhar_id,emp_id):
super().__init__(name, location, age, aadhar_id)
self.emp_id = emp_id
def __repr__(self):
return self.name + self.location + self.emp_id
def accesCurrentCatalog(self):
catalog = Catalog().accessCurrentCatalog
return catalog
def addBook(self,name,author,publish_date,pages):
catalog = self.accesCurrentCatalog()
catalog.addBook(name,author,publish_date,pages)
class Catalog:
def __init__(self, name, location, age, aadhar_id, emp_id):
self.different_book_count = 0
self.books = []
def accessCurrentCatalog(self):
# do stuff
pass
def addBook(self, name, author, publish_date, pages):
# do stuff
pass
现在不需要向库类添加addBook方法,因为它已经从Catalog继承了一个addBook方法
现在可以使用创建库类的实例
from catalog import Catalog
class Library(Catalog):
def __init__(self, name, location, age, aadhar_id, emp_id):
super().__init__(name, location, age, aadhar_id, emp_id)
self.emp_id = emp_id
self.name = name
self.location = location
def __repr__(self):
return self.name + self.location + self.emp_id
如果希望使用accessCurrentCatalog
方法,只需调用my_lib.accessCurrentCatalog()
,因为它从Catalog继承了该方法
如果您想从类中调用它,只需调用
self.accessCurrentCatalog()
,这里不清楚您要实现什么。您正在尝试从另一个python文件中的父类创建子类吗?或者您只是试图从所述类创建对象?Library类和catalog类都是独立的,都驻留在不同的文件中,但都具有名为let say addBook()的公共函数因此,使用catalog类对象,我正在调用addBook函数,该函数将立即将书籍添加到列表中,之后,我使用不同文件中的Library类调用相同的addBook(),它正在创建catalog类的新对象,并使用空列表初始化列表,而不是通过catalog对象添加的列表。。。。。。