bar*_*ker 3 python oop python-3.x
是否有任何场景可以在同一个程序中使用不同的参数以相同的名称编写两个 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)
Run Code Online (Sandbox Code Playgroud)
只会导致使用第二个实例:
second class
3
Run Code Online (Sandbox Code Playgroud)
是的,如果您定义一个与现有类同名的类,它将覆盖该定义。
但第一类的现有实例仍将表现如常。
小例子:
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)
Run Code Online (Sandbox Code Playgroud)
输出:
first class
second class
2
3
Run Code Online (Sandbox Code Playgroud)
如果您从不使用第一个类,像 PyCharm 这样的 IDE 甚至会警告您:
