python学习记录——与C#的差异
1.可存在同名对象
class A:
def __init__(self):
print('this is class.')
def A():
print('this is method.')
a = A()
# this is method.
由于python是边编译边执行的语言,所以只会使用最近的定义。
def A():
print('this is method.')
class A:
def __init__(self):
print('this is class.')
a = A()
# this is class.
2.不存在重载
构造函数:类中只有最后定义的构造函数才有效
class A:
def __init__(self):
pass
def __init__(self, name):
pass
a = A()
# TypeError: A.__init__() missing 1 required positional argument: 'name'
方法:
def test():
print('None')
def test(name):
print(name)
test()
# TypeError: test() missing 1 required positional argument: 'name'
3.类变量
类中定义的变量既可以作为静态变量使用,也可以作为实例变量使用,两者不干涉,通常不作为实例变量使用。
class A:
Name = '66'
def __init__(self, name):
self.Name = name
a = A('77')
print(a.Name)
print(A.Name)
# 77
# 66
4.方法外变量
方法内的变量为局部变量,若是和方法外的变量同名,设置值不会改变方法外的。
name = '77'
def setname(s):
name = s
setname('66')
print(name)
# 77
方法内若是需要对方法外的变量进行读写,需在方法内用 global 标志。
name = '77'
def setname(s):
global name
name = s
setname('66')
print(name)
# 66
5.多继承
class A:
Name = '66'
def __init__(self):
print('this is A.')
class B():
Name = '55'
def __init__(self, name):
print('this is B.')
class C(A, B):
def __init__(self):
print('this is C.')
c = C()
print(c.Name)
# this is C.
# 66
python对于多继承,继承顺序:自己C -> 第一继承A -> 第二继承B,按继承顺序搜索属性和方法等。
class A:
def __init__(self):
print('this is A.')
class B():
Name = '55'
def __init__(self, name):
print('this is B.')
class C(A, B):
pass
c = C()
print(c.Name)
# this is A.
# 55