【问题标题】:Python 3 - classes and private objectsPython 3 - 类和私有对象
【发布时间】:2018-08-24 11:37:59
【问题描述】:

我是 python 新手,不知道为什么这段代码不能运行。我正在尝试创建一个员工类并访问它并从另一个类初始化一个对象,这是类代码:

class employee:

    def __init__(self):
        self.__name
        self.__num


    def employee(self):
        self.__name = "Brian"
        self.__num = 40000

    def employee(self, n ,x):
        self.__name = n
        self.__num = x

    def setName(self, n):
        self.__name = n

    def getName(self):
        return self.__name

    def setNum(self, x):
        self.__num = x

    def getNum(self):
        return self.__num

    def toString(self):
        res = "Name: " + self.__name
        res += "\nNum: " + self.__num

这是测试代码:

import Employee
def main():

    jane = Employee.employee("Jane", 40000)
    brian = Employee.employee()

    print(brian.toString())
    print(jane.toString())

main()

【问题讨论】:

  • 您正在调用对象方法,就好像它们是类方法一样。将所有初始化逻辑移到构造函数中。
  • 1.修复缩进。 2.你期望self.__name中的__init__做什么? 3. Getters 和 Setters 的使用(正如你实现的那样)在 Python 中相当少见。 4.employee方法的第二个定义覆盖了第一个。 5. 整个代码看起来像是在尝试用 Python 编写 Java。
  • 这不是 Python 的方式。看看classes documentation

标签: python class object


【解决方案1】:

首先阅读:https://dirtsimple.org/2004/12/python-is-not-java.html

然后是这个:https://docs.python.org/3/tutorial/classes.html

然后用 Python 的方式重写你的代码:

# employee.py (module names should be all lower)    
class Employee(object):
    # inheriting from `object` is only useful in python2
    # but doesn't break anything in python3

    def __init__(self, name="Brian", num=4000):
        self.name = name
        self.num = num

    def __str__(self):
        # this will be automagically called when trying
        # to make a string out of an Employee
        return "Name: {self.name}\nNum: {self.num}".format(self=self)

    # and that's all. You don't need private attributes nor
    # accessors, Python has a strong support for computed 
    # attributes so you can turn plain attributes into
    # computed ones later if needed (without breaking
    # the client code of course).

和测试代码

# test.py
from employee import Employee

def main():
    # instanciating a class is done by calling it
    jane = Employee("Jane", 40000)
    brian = Employee()

    print(jane)
    print(brian)

if __name__ == "__main__":
    main()

我强烈建议您在尝试用 Python 编写 PHP 或 Java 代码之前至少遵循完整的 Python 教程,这将节省大家的时间。

【讨论】:

    【解决方案2】:

    你正在用 java 风格编写 python。见classes documentation

    class Employee:
    
        # initialize constructor with default arguments
        def __init__(self, name="Brian", num=40000):
            self.name = name
            self.num = num
    
        # you don't need this. this is the work of "__init__" function above
        def employee(self, n ,x):
            self.__name = n
            self.__num = x
    
        def set_name(self, n):
            self.name = n
    
        def get_name(self):
            return self.name
    
        def set_num(self, num):
            self.num = num
    
        def get_num(self):
            return self.num
    
        # tostring equivalent
        def __str__(self):
            # string format
            return "Name: {0}\nNum: {1}".format(self.name, self.num)
    

    测试代码

    def main():
        # you don't need to import employee class if in the same file
        import Employee
    
        # creating instances
        jane = Employee("Jane", 40000)
        brian = Employee()
    
        print(brian)
        print(jane)
    
    
    if __name__=="__main__":
        main()
    

    会打印出来

    >>> Name: Brian
    >>> Num: 40000
    >>> Name: Jane
    >>> Num: 40000
    

    【讨论】:

      【解决方案3】:

      你的类定义对我来说不好看。

      init 方法中,您不会为属性分配任何内容。应该是这样的:

      class employee:
      
          def __init__(self, name, num):
              self.name = name
              self.num = num
      

      此外,您的第二个实例缺少属性。应该是这样的:

      brian = Employee.employee("Brian", 30.000)
      

      您的 ToString 方法也不正确,您不能像这样连接字符串。尝试类似:

      def toString(self):
          res = "Name: {}, Num: {}".format(self.name, self.num)
          return res
      

      【讨论】:

        猜你喜欢
        • 2010-12-30
        • 1970-01-01
        • 1970-01-01
        • 2011-06-30
        • 2015-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多