Python类的重写和私有变量
1、 类的重写
如果子类没有定义__init__()方法,子类初始化的时候就会调用父类的方法,但是当子类定义了__init__()方法,子类就不会调用父类的__init__()方法,
class ren(object):
ren_name = 'ren'
sex = 'F'
def __init__(self,address,age):
self.address = address
self.age = age
print('ren is {0}'.format(self.ren_name))
def get_name(self):
return self.name
def get_sex(self):
return self.sex
class child(ren):
child_name = 'test'
# sex = 'M'
def __init__(self,address,age):
super(child,self).__init__(address,age)
# ren.__init__(self,address,age)
print('my name is {0}'.format(self.child_name))
def hello(self):
print('hello world!')
def get_name(self):
print('todaoy is nice day.')
test = child('beijing',20)
test.hello()
test.get_name()
print(test.get_sex())
print(test.address)
print(test.age)
结果:
ren is ren
my name is test
hello world!
todaoy is nice day.
F
beijing
20
2、 类的私有变量
在Python中可以通过在属性变量名前加上双下划线定义属性为私有属性
_xx 以单下划线开头的表示的是protected类型的变量。即保护类型只能允许其本身与子类进行访问。
__xx 双下划线的表示的是私有类型的变量。只能允许这个类本身进行访问了,连子类也不可以用于命名一个类属性(类变量),私有变量,不允许进行实例化
__xx__定义的是特列方法。用户控制的命名空间内的变量或是属性,如init , __import__或是file 。
class A(object):
_name = 'abc'
__sec = 'F'
def hello(self):
print(self._name)
print(self.__sex)
a = A()
print(a._name)
print(a.__sex)
结果:
abc
Traceback (most recent call last):
File "C:/Users/admin/PycharmProjects/test/class/lei4.py", line 17, in
print(a.__sex)
AttributeError: 'A' object has no attribute '__sex'
class A(object):
_name = 'abc'
__sex = 'F'
def hello(self):
print(self._name)
print(self.__sex)
a = A()
print(a._name)
a.hello()
结果:
abc
abc
F
class A(object):
_name = 'abc'
__sex = 'F'
def hello(self):
print(self._name)
print(self.__sex)
def get_sex(self):
return self.__sex
a = A()
print(a._name)
a.hello()
print(a.get_sex())
结果:
abc
abc
F
F