python - 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()
解决方案
首先阅读: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 教程,这将节省大家的时间。
推荐阅读
- sql - 从没有另一个类似的表中选择行,不满足条件
- kubernetes - 将主机/本地环境变量传递给 Kubectl 'exec' 命令
- r - 防止在缺少日期时连接分开的点
- javascript - Django manifest.json 不加载图标
- javascript - 在 html 页面中嵌入 google drive 视频,以兼容 chrome、firefox 和 IE 的方式
- xml - 如果存在匹配的子元素,则对 XML 子节点进行分组
- r - 通过循环将多条曲线/函数添加到一个ggplot
- java - 从java中的列表json获取值
- c# - c# 配置类和 KeyVault
- javascript - 由于错误 c004e005 无法完成操作