python - 在同一个 python 程序中编写两个具有相同名称的类是否有意义?

标签 python python-3.x oop

在任何情况下,在同一个程序中使用不同参数编写两个具有相同名称的 python 类是否有意义?我正在考虑这个程序,但我的第二个测试类将覆盖第一个。总是这样吗?

class test:
    def __init__(self):
        print("first class")
    def oneplus(self, x):
        print(x + 1)

class test:
    def __init__(self):
        print("second class")
    def twoplus(self, x):
        print(x + 2)

t = test()
t.twoplus(1)  

只会导致使用第二个实例:

second class
3

最佳答案

是的,如果您定义一个与现有类同名的类,它将覆盖该定义。

但第一个类的现有实例仍将照常运行。

小例子:

class test:
    def __init__(self):
        print("first class")
    def oneplus(self, x):
        print(x+1)

t1 = test()

class test:
    def __init__(self):
        print("second class")
    def twoplus(self, x):
        print(x+2)

t2=test()
t1.oneplus(1)
t2.twoplus(1)

输出:

first class
second class
2
3

如果您从不使用第一个类,像 PyCharm 这样的 IDE 甚至会警告您: enter image description here

关于python - 在同一个 python 程序中编写两个具有相同名称的类是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57152976/

相关文章:

python - 我可以部署什么样的图像处理技术来去除人眼图像中的睫毛和眉毛?

python - python中的舍入错误

python - 无法使按钮(使用 tkinter 创建)自动退出

python - 使用 Python 3 动态插入到 sqlite

php - 我该如何改进这段代码

c++ - 虚拟类有什么好处?

python - 如何仅选择值超过阈值的行?

python - 如何处理 f 字符串中的错误?

c++ - c++中的成员模板函数有什么用?

python - Python Kivy中如何通过进入屏幕来调用函数