如何重新设计实例(在父类中)必须保证可以返回子实例的实例?

时间:2019-02-10 10:39:51

标签: python selenium design-patterns

按照标题,我知道这本质上是糟糕的设计,因为父母对孩子一无所知。但是,我处于

  1. 所有孩子都有可重用的行为,这些行为可以从父类中衍生出来
  2. 所有子类需要的那些可重用方法,保证返回当前子类的实例!

我需要所有子类都具有可重复的行为,但还需要具有能够返回孩子实例的父类,这需要完整的重构,但是我如何正确设计它?

我在这里尝试使用composition代替,唯一的问题是所有类都必须声明一个显式的公共API才能使用通用功能,并且将来每个子类都需要声明它。

class BasePage(object):
    # Some Very Common Behaviour goes here.
    # Nothing product specific, just selenium specific 

class ProductBasePage(BasePage):
    # Reusable behaviour here for the product
    # Some of this behaviour in the parent does web-app navigation
    # which merits (quite rightly) to return instances of children
    # pages, for example (CustomersPage, DashboardPage, ProductsPage)
    # but this is clearly flawed and inheritance is not the answer?
    # but how do I keep the functionality that all subclasses need
    # without then declaring it explicitly in every one of them?

class CustomersPage(ProductBasePage):
    # Customer specific behaviour
    # Should have access the common functionality implicitly from the parent

客户页面和扩展产品页面的所有其他页面应具有使用ProductBasePage的所有子类应具有的许多通用功能的能力,而不必每个子类都明确定义该行为。但是,可重用的方法会返回ProductBasePages子类的实例,因为它们的操作可以保证这种行为。

那么我该如何实现呢?我认为继承不是解决问题的办法,但是如何在不明确声明每个类的情况下获得通用功能的可重用性呢?

此问题的解决方案还应避免循环Python导入依赖项。

1 个答案:

答案 0 :(得分:-1)

只需将这些可重用方法放入一个单独的类中,并将其设置为static。然后,子类可以隐式调用这些方法。

如果您不想使用静态方法,请使用普通函数。