首页 > 解决方案 > Python 3 - 类和私有对象

问题描述

我是 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()

标签: pythonclassobject

解决方案


首先阅读: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 教程,这将节省大家的时间。


推荐阅读