Python OOP工厂模式

时间:2015-09-23 19:36:06

标签: python design-patterns factory

我还在学习OOP设计模式,到目前为止我所阅读的所有内容都说工厂模式是常用的。我仍在努力学习这种模式。对于我的程序,我正在创建一个名为" person"我的工厂打电话给#34; personFactory"应该让你创造不同类型的人(用户,客户,管道工等......)。使用我当前的代码,我收到此错误:

AttributeError: 'NoneType' object has no attribute 'fName'

这是我的代码:

person.py

import abc

class person:
    __metaclass__ = abc.ABCMeta
    fName = ""
    mName = ""
    lName = ""
    address = ""
    city = ""
    state = ""
    zipcode = ""
    email = ""
    phone = ""
    dob = None

personFactory.py

from person import person

class personFactory(person):

    def createUser(self):
        uName = ""
        password = ""
        role = ""
        def __init__(self,uName,password,role):
            self.uName = uName
            self.password = password
            self.role = role
        def login(uName,password):
            if(uName == self.uName and password == self.password):
                return "Logged In"
            else:
                return "Did not log in"
        def logout():
            return "Logout"

    def createCustomer(self):
        items = []
        balace = 0
        def __init__(self,balance):
            self.balance = balance
        def AddToCart(item):
            self.items.append(item)
            print("Item added")
        def Order(items):
            totalprice = 0
            for item in items:
                totalprice =+ item.price
            return totalprice
        def Pay(payment):
            self.balance =- payment
            return self.balance

main.py

import personFactory

class main():
    pf = personFactory.personFactory()
    user1 = pf.createUser()
    user1.fName = "John"
    user1.lName = "Smith"
    user1.uName = "jSmith"
    user1.password = "Jamestown"

    customer1 = pf.createCustomer()
    customer1.fName = "George"
    customer1.lName = "Washington"
    customer1.balance = 100

main()

我不确定为什么fName是NoneType。我究竟做错了什么?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您在create_user方法中有构造函数。正如Ignacio所说, init 函数必须在create_user函数之外,为了在创建时传递名称,传递和角色到person_factory对象。

或者,您可以将所有这些值作为参数传递给create_user方法,并使类构造函数不再起作用。

可能是这样的......

class personFactory(person):

  def __init__(self,uName,password,role):
        self.uName = uName
        self.password = password
        self.role = role

def createUser(self):
    user = Person()
    user.type = "user"
    user.uName = self.uName
    user.password = self.password
    user.role = role
    return user

或者...

class personFactory(person):

  def createUser(self, uName, password, role):
       user = Person()
       user.type = "user"
       user.uName = uName
       user.password = password
       user.role = role
       return user

我还建议您使用继承并根据代表每个对象的抽象类创建具体类。

...一样

class User(Person):

      def __init__(name, password, role):
          self.name = name
          self.type = "User"
          self.password = password

因此,您可以拥有User类和Customer类,并且工厂的每个方法都可以创建相应的对象,而不是常规Person。