【发布时间】:2019-12-29 20:09:00
【问题描述】:
我在 python 中有两个类:
- ClassA 在其他类似方法中从较大的字符串中获取字符串
- ClassB 在其他类似方法中从较大的字符串中删除字符串
比这更复杂,这就是我使用类的原因。最初我在一个类中拥有所有方法,但它变得有点不可读,我想在逻辑上将方法分成两个部分,所以我将一些函数移到 ClassB 中。 ClassA 和 ClassB 没有父子关系,并且相似,但我希望它们保持分离。
我希望能够从 ClassA 访问 ClassB 方法。有没有一种方法可以让我从 Class A 访问 ClassB 方法而无需创建新对象;通过将 ClassB 的方法导入或添加到 Class A 之类的操作。
class readText:
def __init__(self, book):
self.book = book
def getPageFromNum(self):
##Some Code
def getLineFromPage(self):
##Some Code
class modifyText:
def __init__(self, book):
self.book = book
def removeLine(self, lineNumber):
##Some Code
def removeWordInstances(self, word)
##Some Code
readableBook = readText(book)
##Accessing methods of the objects classes
readableBook.getLineFromPage()
##I want to be able to access methods of the other class modifyText in the same way like below
readableBook.removeLine(50)
我有第二个问题,假设问题 1 是可能的。到目前为止,我在 classA 中有大约 30 个方法,在 classB 中有 15 个方法。在初始化 classA 对象时,我可以有一个可选参数来添加其他方法。我总是需要对字符串使用 ClassA 方法,但我并不总是需要对字符串使用 ClassB 方法。这是否会显着提高程序的效率?
【问题讨论】:
-
如果方法是实例方法,而不是类或静态方法,则必须在 classA 中使用 classB 的对象,或者使用父子对象
标签: python